package com.****.test; import com.****.config.SpringConfig; import com.****.logger.Logger; import com.****.service.AccountService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.InvocationHandler; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.lang.reflect.Method; //启动容器 @RunWith(SpringJUnit4ClassRunner.class) //向容器中添加配置 @ContextConfiguration(classes = SpringConfig.class) public class AccountServiceTest { @Autowired private AccountService accountService; @Autowired private Logger logger; @Test public void SaveTest() { //1.创建目标对象 已经有啦 直接拿过来accountService //2.编写增强逻辑 InvocationHandler invocationHandler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //2.1调取目标方法 Object obj = null; logger.method1(); try { obj = method.invoke(accountService, args); } catch (Exception e) { logger.method3(); } logger.method2(); return obj; } }; //3.创建代理对象 //3.1创建增强器 Enhancer enhancer = new Enhancer(); //3.2设置父类 enhancer.setSuperclass(AccountService.class); //4.3设置增强逻辑 enhancer. setCallback(invocationHandler); //4.3创建代理对象 AccountService proxyInstance =(AccountService) enhancer.create(); /*AccountService proxyInstance = (AccountService) Proxy.newProxyInstance( accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), invocationHandler );*/ //4.让代理对象工作 proxyInstance.save(); } }
【cglib代理】 四个步骤演示
于 2022-07-26 01:22:13 首次发布