开发者

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

I'va a ServiceImpl with is annotated with @Service stereotype of Spring and have two me开发者_JAVA技巧thods 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?


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜