Spring源码-动态代理底层原理

一、动态代理开发步骤

 1、创建原始对象
    <bean id ="userService"  class ="userServiceImpl">
    
 2、额外功能
   MethodBeforeAdvice接口
   额外功能写在接口实现类中,原始方法执行之前
   
 		public class Before implements MethodBeforeAdvice{
				@Override
				public void before(Method method ,Object[] args ,Object target)throws Throwable			
		}
		<bean id ="before"  class ="com.Before">
		
	3、定义切入点
      切入点:额外功能加入的位置
      目的:加给谁
   <aop:config>
   		<aop:pointcut id ="pc"  expression="execution(* *(..))">
   </aop:config>
   
   
   4、组装(23整合)
   <aop:advisor advice-ref="before"  pointcut-ref ="pc">
   
   
   5、调用
   Application ctx = new ClassPathXmlApplicationContext("/applicationContext.xml")
   // 通过原始对象的id 获取代理对象
   UserService uservice = (UserService)ctx.getBean("userService");
   
   			

二 、AOP底层原理


1. 原始对象
2. 额外功能 (MethodInterceptor)
3. 切⼊点
4. 组装切⾯ (额外功能+切⼊点)


2.1 cglib

CGlib创建动态代理的原理:⽗⼦继承关系创建代理对象,原始类作为⽗类,代理类作为⼦类,这样既可以保证2者⽅法⼀致,同时在代理类中提供新的实现(额外功能+原始⽅法)

     
  // 配置cglib动态代理 :proxy-target-class="true"

	Enhancer enhancer = new Enhancer();
	enhancer.setClassLoader ("随便一个classLoader");
	enhancer.setSuperClass(userService.getClass());
	
	MethodInceptor methodInceptor = new MethodInceptor(
				Object o,
				Method method,
				Object args,
				MethodProxy methodProxy
	
	){
				Object ret = method.invoke();
				return ret ;
				
	}
	
	enhancer.setCallback(interceptor);
	UserService userServiceProxy = (UserService) enhancer.create();
	
	
	







2.2 jdk

在这里插入图片描述
在这里插入图片描述

  // 1、创建原始对象
  UserService userService = new UserServiceImpl();
  
  //2、 创建JDK动态代理  
  // 内部类实现接口方式
  InvocationHandler handler = new InvocationHandler (){
  		@Override
  		public Object invoke (Object porxy ,Mehtod method ,Object [] args ) throws Throwable{
  	      // do something 		
  				Object ret = method.invoke(userService ,args);
  				// do something
  				return ret ;
  			
  		}
  }
  UserService userServiceProxy = new Proxy.newProxyInstance(
        UserServiceImpl.class.getClassLoad(), 
        userService.getClass.getInterfaces(),hander
  );
  userServiceProxy.login("zm " ,"123456");
  
  
  利用的拦截去原理InvocationHandler





2.3 aspectj


注意事项 :Spring AOP 默认代理实现是JDK ,springboot AOP代理默认实现时cglib

2.4 cglib和jdk动态代理区别

在这里插入图片描述

1、目标对象生产了接口,默认用JDK动态代理

三、注意事项

3.1 代理对象中调用原始对象
   
   
   xxx  implment ApplicationAware{
   private Application ctx;
   
   @Override
   pulbic void setApplicationContext (ApplicationContext applicationContext) throws BeansException
   	{
   	this.ctx = applicationContext;
   	}
   
   }
  

3.2 Spring 工厂如何加工原始对象

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值