在上面的两种情况实现AOP中的目标对象UserManagerImpl都实现了接口,如果没有实现接口,该如何做呢?使用CGLIB。
下面简单介绍spring对AOP的支持的几种情况:
1、如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP
2、如果目标对象实现了接口,可以强制使用CGLIB实现AOP
3、如果目标对象没有实现了接口,必须采用CGLIB库,spring会自动在JDK动态代理和CGLIB之间转换
如何强制使用CGLIB实现AOP?
* 添加CGLIB库,SPRING_HOME/cglib/*.jar
* 在spring配置文件中加入<aop:aspectj-autoproxy proxy-target-class="true"/>
下面我们基于上面来做一个使用CGLIB的例子,我们只需修改UserManagerImpl和配置文件,代码如下:
目标对象UserManagerImpl不实现接口:
public class UserManagerImpl { public void addUser(String username, String password) { System.out.println("----UserManagerImpl.addUser()----"); } public void deleteUser(int id) { System.out.println("----UserManagerImpl.deleteUser()----"); } public String findUserById(int id) { System.out.println("----UserManagerImpl.findUserById()--"); return null; } public void modifyUser(int id, String username, String password) { System.out.println("----UserManagerImpl.modifyUser()----"); } |
applicationContext.xml
<aop:aspectj-autoproxy proxy-target-class="true"/> <bean id="securityHandler" class="spring.SecurityHandler"/> <bean id="userManager" class="spring.UserManagerImpl"/> <aop:config> <aop:aspect id="security" ref="securityHandler"> <aop:pointcut id="allAddMethod" expression="execution(* spring.UserManagerImpl.add*(..))" /> <aop:before method="checkSecurity" pointcut-ref="allAddMethod"/> </aop:aspect> </aop:config> |
测试端代码:
public class Client { public static void main(String[] args) { BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); UserManagerImpl userManager = (UserManagerImpl)factory.getBean("userManager"); userManager.addUser("张三", "123"); } }
|
JDK动态代理和CGLIB字节码生成的区别?
* JDK动态代理只能对实现了接口的类生成代理,而不能针对类
* CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法,因为是继承,所以该类或方法最好不要声明成final