spring中CGLIB代理(CGLIB字节码)

spring对AOP的支持-----知识点:

JDK的动态代理:主要是针对实现了接口的类生成代理 

CGLIB:是针对类生成代理,针对指定的类生成一个子类,覆盖里面的方法,所以指定的类不能是final包括方法

实例:目标对象

package com.lovo.spring;
 
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.findUser()--------");
		return null;
	}

	public void modifyUser(int id, String username, String password) {
	System.out.println("---------userManagerImpl.modifyUser()--------");

	}
//private void checkSecurity(){
//	System.out.println("---------userManagerImpl.checkSecurity()--------");
//}
}

 代理对象:

package com.lovo.spring;

import org.aspectj.lang.JoinPoint;



public class SecurityHandler {

	private void checkSecurity(){

		System.out.println("---------------------------checkSecurity222222222222222");
	
	
	}

}

 

applicationContext.xml配置文件:

<!--  	可以不配置:spring会用到CGLIB库,但是必须导入库

<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
-->
	<bean id="securityHandler" clss="com.lovo.spring.SecurityHandler"/>           
	
	<bean id="userManager" class="com.lovo.spring.UserManagerImpl"/>
<aop:config>
	<aop:aspect id="myAspect" ref="securityHandler">
			<aop:pointcut id="allAddMethod" expression="execution(* com.lovo.spring.UserManagerImpl.add*(..))"/>
			<aop:before method="checkSecurity" pointcut-ref="allAddMethod"/>
	</aop:aspect>

</aop:config>

 1:如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP

2:目标对象实现了接口,可以强制使用CGLIB实现AOP

3:如目标对象没有实现接口,必须采用CGLIB库,spirng会自动在JDK动态代理和CGLIB之间转换

测试类:

package com.lovo.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ClientTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	/**1111*/BeanFactory bf = new ClassPathXmlApplicationContext("applicationContext.xml");
	UserManagerImpl userManager =  (UserManagerImpl) bf.getBean("userManager");
		userManager.addUser("aa", "aa");
//		userManager.deleteUser(2);
	
	}

}

 

在这里:可以在111处采用断点:可以看到userManager对象是一个CGLIB代理,

userManagerImp1$$EnhancerByCGLIB$$..........

如果是实现了接口的JDK动态代理的话:

这里的userManager就是:$Proxy0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值