Whats the best way to inject same instance of service in service for Spring AOP

你说的曾经没有我的故事 提交于 2019-12-07 14:44:22

问题


I'va a ServiceImpl with is annotated with @Service stereotype of Spring and have two methods in it each one is annotated with custom annotations which are intercepted by Spring.

@Service    
public class ServiceImpl implements Service{

       @CustomAnnotation
       public void method1(){
       ...
       }

       @AnotherCustomAnnotation
       public void method2(){
        this.method1();   
        ...
       }
    }
}

Now Spring uses proxy based AOP approach and hence as I'm using this.method1() interceptor for @CustomAnnotation will not able to intercept this call, We used to inject this service in another FactoryClass and in that way we were able to get the proxy instance like -

  @AnotherCustomAnnotation
    public void method2(){
        someFactory.getService().method1();   
        ...
    }

I'm now using Spring 3.0.x, which is the best way to get the proxy instance?


回答1:


The other alternative is to use AspectJ and @Configurable. Spring seems to be going towards these days (favoring).

I would look into it if you are using Spring 3 as it is faster (performance) and more flexible than proxy based aop.




回答2:


Both methods are inside the same proxy, whereas the AOP functionality just enriches calls from the outside (see Understanding AOP Proxies). There are three ways for you to deal with that restriction:

  1. Change your design (that's what I would recommend)
  2. Change proxy type from JDK-proxy to proxy-target-class (CGLib-based subclassing) Nope, that doesn't help, see @axtavt's comment, it would have to be static AspectJ compilation.
  3. Use ((Service)AopContext.currentProxy()).method1() (Works, but is an awful violation of AOP, see the end of Understanding AOP Proxies)



回答3:


You could make your ServiceImpl class implement the BeanFactoryAware interface, and lookup itself thanks to the provided bean factory. But this is not dependency injection anymore.

The best solution is to put method1 in another service bean, which would be injected in your existing service bean and to which your existing service bean would delegate.



来源:https://stackoverflow.com/questions/5091187/whats-the-best-way-to-inject-same-instance-of-service-in-service-for-spring-aop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!