一、动态代理开发步骤
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、组装(2、3整合)
<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;
}
}