AOP通知无法切入指定方法

AOP通知,切入指定方法时拦截不到,可能是拦截的方法本身是被本类的其他方法调用的,根据AOP反射原理是无法拦截本类中方法调用的方法的。如:

 1 class AImpl implements AIf {
 2 
 3   sleep(){
 4 
 5     say();
 6 
 7   }
 8 
 9   say(){
10 
11     System.out.println("我是被本类的其它方法调用的");
12 
13   }
14 
15 }

 

AImpl类中sleep()方法中调用了本类中的say()方法,如果用aop切入点去拦截sleep()方法,则可以正常拦截,若拦截say()方法,则无法拦截。解决方案为使用动态代理,流程如下:

 

①:创建代理接口

1 public interface BeanSelfAware {  
2     void setSelf();  
3 }

②:实现代理接口,获得上下文环境的对象,把自身对象注入给本类

 1  class AImpl implements AIf,BeanSelfAware {
 2      @Autowired  //①  注入上下文  
 3         private ApplicationContext context;
 4         
 5         private AIf aIf;
 6    sleep(){
 7  
 8     aIf.say();
 9  
10    }
11 
12   say(){
13  
14      System.out.println("我是被本类的其它方法调用的");
15 
16   }
17     //获得自身对象
18     @PostConstruct
19     public void setSelf() {
20          this.aIf=           context.getBean(AIf.class); 
21     }
22  
23  } 

这样 aop就可正常拦截say()方法了

 

posted @ 2014-10-30 15:35  闻鸡睡觉  阅读(1129)  评论(0编辑  收藏  举报