如何在使用spring安全注解时调用不安全的代理?
问题描述:
我在我的项目中使用了spring security annotations。有些情况下,我想调用注释对象的无安全版本。默认情况下,Spring为注释对象创建一个启用安全性的代理并将其用于代码中的自动装配,有没有什么方法可以使用spring来实现?
这样做的一个显而易见的方法是手动创建对应于每个类的代理类,我希望此功能对这些方法进行了注释,并且这些方法的实现只是将其委托给实际对象。如何在使用spring安全注解时调用不安全的代理?
答
正如在JDK代理的情况下的一个选项,你可以在运行时得到实际的bean:
MyBean proxy;
if(AopUtils.isJdkDynamicProxy(proxy)) {
MyBean actualInstance = (MyBean) ((Advised)proxy).getTargetSource().getTarget()
}
actualInstance.doSomethingSecured(); // no advice related to this method will be called
// so your security annotation will be ignored (transactions, cache, and everething that requires AOP too...)
但是从视图具有手动代理方式的建筑点看起来更小的误差phrone(除非你绝对相信你不需要安全性和所有其他可能的方面)。
您可以使用泛型提高可读性:
MyBean actualInstance = extractProxyTarget(proxy, proxy.getClass());
actualInstance.doSomethingSecured();