spring面向切面编程--JDK代理和CGLIB代理

来源:互联网 发布:美工代码生成器 编辑:程序博客网 时间:2024/05/14 03:55
spring对AOP的支持 

1、如果目标对象实现了接口,默认会采用JDK的动态代理机制实现AOP 
2、如果目标对象实现了接口,可以强制使用CGLIB实现AOP 
3、如果目标对象没有实现接口,必须使用CGLIB生成代理,spring会自动在CGLIB和JDK动态代理之间切换 

4.如何强制使用CGLIB生成代理? 
* 添加CGLIB库,SPRING_HOME/lib/cglib/*.jar 
* 在spring的配置文件中加入: 
<aop:aspectj-autoproxy proxy-target-class="true"/> 

JDK代理和CGLIB代理的区别? 
* JDK代理只能对实现了接口的类生成代理,而不能针对类 
* CGLIB是针对类实现代理的,主要对指定的类生成一个子类,并覆盖其中的方法, 
  因为是继承,所以不能使用final来修饰类或方法<aop:aspectj-autoproxy proxy-target-class="true"/> 


在什么情况下,Spring使用CGLIB做代理? 
1.在AOP(二)基础上如果将UserManagerImpl.java修改为如下,则Spring会自动使用CGLIB做动态代理; 
Java代码  收藏代码
  1. package com.wlh.spring;  
  2.   
  3.  //public class UserManagerImpl implements UserManager {  
  4.  public class UserManagerImpl{  
  5.      //目标类不实现接口的情况下,Spring自动使用CGLIB做代理  
  6.     public void addUser(String username, String pwd) {  
  7.       System.out.println("====addUser()=====");  
  8.     }  
  9.   
  10.     public void delUser(int id) {  
  11.          System.out.println("====delUser()=====");  
  12.     }  
  13.   
  14.     public void findUser(int id) {  
  15.          System.out.println("====findUser()=====");  
  16.     }  
  17.   
  18.     public void updateUser(int id, String username, String pwd) {  
  19.          System.out.println("====updateUser()=====");  
  20.     }  
  21.   
  22. }  




2、如果UserManagerImpl.java类步变,仍然实现了接口UserManager,然后我们在配置文件中,添加一个标签:<aop:aspectj-autoproxy proxy-target-class="true"/> 
Spring也会使用CGLIB做代理类:
 
<!--<aop:aspectj-autoproxy proxy-target-class="true"/> 支持CGLIB代理 --> 

<bean id="userManager" class="com.wlh.spring.UserManagerImpl" /> 

<bean id="securityHandler" class="com.wlh.spring.SecurityHandler" /><!-- 切面类 --> 
<aop:config> 
<aop:aspect id="securityAspect" ref="securityHandler"><!-- 引用切面类 --> 
<!-- 表达式方法声明匹配被切入的类及其方法 --> 
<aop:pointcut id="applyMethod" 
expression="execution(* com.wlh.spring.*.add*(..)) || execution(* com.wlh.spring.*.del*(..))" /> 
<aop:before pointcut-ref="applyMethod" 
method="checkSecurity" /><!-- 声明切面类的要切入方法 --> 
</aop:aspect> 

</aop:config> 


原文地址:

http://www.iteye.com/topic/323547




原创粉丝点击