AOP
第一随记:
在aop中,对于是否用Clib或者用JDK动态代理,是根据目标类是否存在实现接口,如果实现接口就会用JDK,r如果未实现接口,就会
Cglib,但是为了解耦和,大部分都会用目标类实现接口即用JDK动态代理,因此在使用Spring 时,在从容器中获取代理对象时就要注意了
注意:上面的话不正确,不完全正确
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @ComponentScan("com") /** * proxyTargetClass = true 如果加了这个条件会强制使用Cglin动态代理,默认是false */ @EnableAspectJAutoProxy(proxyTargetClass = true) public class AppConfig { }
第二部分:AOP源码一步一步
在测试处打第一个断点:
1. JDK :目标类与代理类时同级关系(兄弟关系),所以获取的代理对象类型不能使目标类行,而应该是接口类型
ApplicationContext ac = new ClassPathXmlApplicationContext("com/abc/test8/myThree/applicationContext.xml"); //此处为JDK代理 Calculator proxy = ac.getBean("calculatorImpl",Calculator.class); String name = proxy.getClass().getName(); System.out.println(name);
2.Cglib:这个直接可以获取目标类型
ApplicationContext ac = new ClassPathXmlApplicationContext("com/abc/test8/myThree/applicationContext.xml"); CalculatorImpl proxy =ac.getBean(CalculatorImpl.class); String name = proxy.getClass().getName(); System.out.println(name);