Is possible to get the proxy of a given object in Spring? I need to call a function of a subclass. But, obviously, when I do a direct call, the aspects aren't applied. Here's an example:
public class Parent { public doSomething() { Parent proxyOfMe = Spring.getProxyOfMe(this); // (please) Method method = this.class.getMethod("sayHello"); method.invoke(proxyOfMe); } } public class Child extends Parent { @Secured("president") public void sayHello() { System.out.println("Hello Mr. President"); } }
I've found a way of achieving this. It works, but I think is not very elegant:
public class Parent implements BeanNameAware { @Autowired private ApplicationContext applicationContext; private String beanName; // Getter public doSomething() { Parent proxyOfMe = applicationContext.getBean(beanName, Parent.class); Method method = this.class.getMethod("sayHello"); method.invoke(proxyOfMe); } }
@AspectJAutoProxy. Fashioned after Spring XML's <aop:aspectj-autoproxy> , @AspectJAutoProxy detects any @Aspect beans and generates proxies as appropriate to weave the advice methods in those aspects against other beans in the container.
AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy. Weaving: linking aspects with other application types or objects to create an advised object.
Spring AOP is a proxy-based AOP framework. This means that to implement aspects to the target objects, it'll create proxies of that object. This is achieved using either of two ways: JDK dynamic proxy – the preferred way for Spring AOP.
This hack is extremely awkward, please consider refactoring your code or using AspectJ weaving. You may feel warned, here is the solution
AopContext.currentProxy()
JavaDoc. I blogged about it here and here.
AopContext.currentProxy()
as suggested by Tomasz will work. A more generic solution, that will work outside of the proxied class is to cast the object to org.springframework.aop.framework.Advised
and get .getTargetSource().getTarget()
The former (getting the real object from the proxied object) is something that you should not really need. On the other hand getting the target proxy might be useful in some utility class that inspects existing beans in order to add some feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With