Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get AOP proxy from the object itself

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);     } } 
like image 307
sinuhepop Avatar asked Sep 20 '11 09:09

sinuhepop


People also ask

What does AOP AspectJ Autoproxy /> do?

@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.

What is proxy object in Spring AOP?

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.

Is Spring AOP proxy-based?

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.


2 Answers

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.

like image 154
Tomasz Nurkiewicz Avatar answered Nov 11 '22 11:11

Tomasz Nurkiewicz


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.

like image 38
Bozho Avatar answered Nov 11 '22 10:11

Bozho