1:静态代理,需要自己写一个代理类,
UserService接口
public interface UserService {
public void add();
}
UserServiceImpl实现类
public void add(){
System.out.println("往数据库添加数据。。。");
}
静态代理类
public class UserServiceProxy {
private UserService userService;
public UserServiceProxy(UserService userService){
this.userService = userService;
}
public void add(){
System.out.println("静态代理开启事务");
userService.add();
System.out.println("静态代理关闭事务");
}
}
测试类:
public class Test {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
// userService.add();
UserServiceProxy userServiceProxy = new UserServiceProxy(userService);
userServiceProxy.add();
}
}
2:动态代理,分为JDK动态代理和CGLIB动态代理,JDK动态代理需要实现接口InvocationHandler ,因为在需要继承proxy类获得有关方法和InvocationHandler构造方法传参的同时,java不能同时继承两个类,我们需要和想要代理的类建立联系,只能实现一个接口。
动态代理类
// 每次生成动态代理类对象时,实现了InvocationHandler接口的调用处理器对象
public class InvocationHandlerImpl implements InvocationHandler {
private Object target;// 这其实业务实现类对象,用来调用具体的业务方法
// 通过构造函数传入目标对象
public InvocationHandlerImpl(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
System.out.println("使用JDK动态代理 开启事务");
result = method.invoke(target, args);
System.out.println("使用JDK动态代理 关闭事务");
return result;
}
}
测试类
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
UserService userService = new UserServiceImpl();
InvocationHandlerImpl invocationHandlerImpl = new InvocationHandlerImpl(userService);
ClassLoader loader = userService.getClass().getClassLoader();
Class<?>[] interfaces = userService.getClass().getInterfaces();
// 主要装载器、一组接口及调用处理动态代理实例
UserService newProxyInstance = (UserService) Proxy.newProxyInstance(loader, interfaces, invocationHandlerImpl);
newProxyInstance.add();
}
```