合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
**1.UserService** ~~~ package com.nobb.service; /** * 动态代理实验 */ public interface UserService { void save(); void delete(); void update(); void find(); } ~~~ **2.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"); } } ~~~ **3.UserServiceDynamicProxyFactory** ~~~ package com.nobb.proxy; import com.nobb.service.UserService; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class UserServiceDynamicProxyFactory implements InvocationHandler{ //被代理对象 private UserService target; //UserServiceImpl //在构造器注入了目标对象 public UserServiceDynamicProxyFactory(UserService target){ this.target = target; } //创建代理类对象 -> 生成接口实现类 //参数1: 类加载器,加载生成的类 //参数2: 指定待实现的接口,因为一个类可以实现多个接口,传入接口class数组 //参数3: 指定接口实现类实现方法的行为 public UserService getUserService(){ return (UserService) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{UserService.class}, this); } //指定代理类的行为 //参数1:代理对象 //参数2: 指定调用的是接口中的哪一个方法 //参数3: 方法执行的参数 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //开启事务 System.out.println(method); System.out.println("开启事务"); //执行业务代码 Object o = method.invoke(target, args); //关闭事务 System.out.println("关闭事务"); return o; } } ~~~ **4.Demo1** ~~~ package com.nobb.proxy; import com.nobb.service.UserService; import com.nobb.service.UserServiceImpl; /** * 动态代理测试类 */ public class Demo1 { public static void main(String[] args) { UserService target = new UserServiceImpl(); //拿到接口的实现类 UserServiceDynamicProxyFactory factory = new UserServiceDynamicProxyFactory(target); UserService userService = factory.getUserService(); //实际执行的是代理类 userService.save(); // userService.delete(); // userService.update(); // userService.find(); System.out.println(userService instanceof UserService); } } ~~~