原理分析
CGLIb
OrderService orderService = new OrderService();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(OrderService.class);
//如果是需要所有方法都执行的setCallback
//在setCallbacks 如果设置了多个Callback 那么必须setCallbackFilter
enhancer.setCallbacks(new Callback[]{
new MethodInterceptor() {
//第一个参数是代理对象 官方文档上写明了 如果invoke传入o则发生循环调用
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("执行了代理内容1");
return methodProxy.invoke(orderService, objects);
}
},
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("执行了代理内容2");
return methodProxy.invoke(orderService, objects);
}
},
});
enhancer.setCallbackFilter(new CallbackFilter() {
@Override
public int accept(Method method) {
//指这个方法所执行代理intercept 的下标
return 1;
}
});
OrderService orderServiceProxy = (OrderService) enhancer.create();
System.out.println(orderServiceProxy.getOrderId());
动态代理
BillApi phoneBill = new PhoneBillImpl();
BillApi phoneBillProxy = (BillApi) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{BillApi.class}, new InvocationHandler() {
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
System.out.println("执行方法前代理");
return method.invoke(phoneBill, objects);
}
});
System.out.println(phoneBillProxy.getId());
Spring 统一封装
一个是继承,一个是实现,都有各自适用的场景
但是都是一个实例方法的增强
所以统一封装便于使用文章来源:https://www.toymoban.com/news/detail-632713.html
接口类代理
BillApi phoneBill = new PhoneBillImpl();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(phoneBill);
proxyFactory.addAdvice(new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行前代理");
}
});
proxyFactory.addAdvice(new AfterReturningAdvice() {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行后代理");
}
});
BillApi proxy = (BillApi)proxyFactory.getProxy();
proxy.userName();
非接口代理:
OrderService orderService = new OrderService();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(orderService);
proxyFactory.addAdvice(new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行前代理");
}
});
proxyFactory.addAdvice(new AfterReturningAdvice() {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行后代理");
}
});
OrderService proxy = (OrderService)proxyFactory.getProxy();
proxy.getOrderId();
屏蔽了底层的代理工具的切换
抽象了代理方法Advice
不需要再手动调用:被代理类(原型)的方法文章来源地址https://www.toymoban.com/news/detail-632713.html
到了这里,关于004-Spring AOP源码分析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!