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

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




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值