合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
**1.UserServiceImpl** ~~~ package com.nobb.service; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService{ public String test(){ return "success"; } @Override public void save() { // int i = 1/0; System.out.println("save"); } @Override public void delete() { System.out.println("delete"); } @Override public void update() { System.out.println("update"); } @Override public void find() { System.out.println("find"); } } ~~~ **2.UserServiceCGLibProxyFactory** ~~~ package com.nobb.proxy; import com.nobb.service.UserService; import com.nobb.service.UserServiceImpl; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.InvocationHandler; import java.lang.reflect.Method; /** * CGlib代理 */ public class UserServiceCGLibProxyFactory implements InvocationHandler { private UserService target; public UserServiceCGLibProxyFactory(UserService target){ this.target = target; } //返回UserService的代理类对象 public UserService getUserService(){ //创建Enhancer对象 Enhancer enhancer = new Enhancer(); //指定父类 是类 非接口 enhancer.setSuperclass(UserServiceImpl.class); //指定代理类"行为" enhancer.setCallback(this); //通过Enhancer对象生成CGlib代理对象 return (UserService) enhancer.create(); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("开启事务"); Object invoke = method.invoke(target,args); System.out.println("关闭事务"); return invoke; } } ~~~ **3.测试代码** ~~~ package com.nobb.proxy; import com.nobb.service.UserService; import com.nobb.service.UserServiceImpl; /** * CGlib代理 测试类 */ public class Demo2 { public static void main(String[] args){ UserService target = new UserServiceImpl(); UserServiceCGLibProxyFactory factory = new UserServiceCGLibProxyFactory(target); UserService userService = factory.getUserService(); userService.save(); System.out.println(userService instanceof UserServiceImpl); } } ~~~