JDK 代理
proxy:代理对象
method:代理对象执行的方法
args:方法的参数
public class JdkProxyTest {public static void main(String[] args) {UserServiceInterface proxyInstance = (UserServiceInterface) Proxy.newProxyInstance(JdkProxyTest.class.getClassLoader(), UserService.class.getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("代理前的逻辑...");Object result = method.invoke(new UserService(), args);System.out.println("代理后的逻辑...");return result;}});proxyInstance.test();}}
Spring 代理
Advise:代理逻辑(通知)
PointCut:切点(针对什么样的方法)
Advistor:Advise + PointCut
public class SpringProxyTest {public static void main(String[] args) {ProxyFactory proxyFactory = new ProxyFactory();// proxyFactory.setOptimize(true); // CGLIB 动态代理// proxyFactory.setProxyTargetClass(true); // CGLIB 动态代理// 目标对象proxyFactory.setTarget(new UserService()); // CGLIB 动态代理// proxyFactory.addInterface(UserServiceInterface.class); // 如果设置了接口,就会使用 JDK 动态代理// 代理逻辑proxyFactory.addAdvice(new MethodBeforeAdvice() {@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println(method.getName() + " 方法执行前的逻辑...");}});// 代理逻辑proxyFactory.addAdvice(new AfterReturningAdvice() {@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println(method.getName() + " 方法返回后的逻辑...");}});// 生成代理对象// UserServiceInterface proxy = (UserServiceInterface) proxyFactory.getProxy();UserService proxy = (UserService) proxyFactory.getProxy();proxy.test();}}
总结
如果 Spring 中的一个 bean
- 如果没有实现任何接口,默认使用 CGLIB,否则使用 JDK 动态代理
- 如果设置了 proxyTargetClass 为 true,则强制使用 CGLIB
