首页 > 解决方案 > 使用 setTarget 和 ProxyFactory(Object target) 方法为同一对象创建不同的 Aop 代理

问题描述

这是代码

//IUserService is a interface
IUserService userService=new UserServiceImpl();

NameMatchMethodPointcut pointcut=new NameMatchMethodPointcut();
pointcut.addMethodName("save*");


LogAdvice logAdvice=new LogAdvice();


Advisor advisor=new DefaultPointcutAdvisor(pointcut,logAdvice);

//when set the target in constructor JdkDynamicAopProxy will be created
//ProxyFactory proxyFactory=new ProxyFactory(userService);
ProxyFactory proxyFactory=new ProxyFactory();
proxyFactory.addAdvisor(advisor);
//if use setTarget to set the target ObjenesisCglibAopProxy will be created
proxyFactory.setTarget(userService);

IUserService proxy=(IUserService) proxyFactory.getProxy();

proxy.queryUser();
proxy.saveUser();

setTargetset target using or in之间的区别在于Constructor,当 in ConstructortheresetInterfaces(ClassUtils.getAllInterfaces(target));但 not in 时setTarget,我不知道为什么,因为我认为因为IUserService是一个接口,JdkDynamicAopProxy所以无论我如何设置目标都应该创建?spring源码版本为5.0.0.BUILD-SNAPSHOT

标签: springspring-aop

解决方案


推荐阅读