接口
public interface UserService {void selectAll();
}
实现类(需要增加业务)
public class UserServiceImpl implements UserService{@Overridepublic void selectAll() {System.out.println("查询");}
}
静态代理
代理类
public class UserProxy implements UserService {// 持有具体业务实现private UserService userService;public void setUserService(UserService userService) {this.userService = userService;}@Overridepublic void selectAll() {System.out.println("不改变原有代码,进行增强");// 执行原有逻辑userService.selectAll();}
}
测试
public static void main(String[] args) {UserProxy userProxy = new UserProxy();// 代理具体业务实现userProxy.setUserService(new UserServiceImpl());// 执行增强业务userProxy.selectAll();
}
动态代理
代理类
public class ProxyInvocationHandler implements InvocationHandler {// 持有具体业务实现private Object object;public void setUserService(Object object) {this.object= object;}public Object getProxy(){// 让代理类实现具体实现类(UserServiceImpl)的接口(UserService),并重写接口方法,返回代理对象return Proxy.newProxyInstance(this.getClass().getClassLoader(), object.getClass().getInterfaces(), this);}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("这里进行增强");// 代理类执行接口方法时,执行具体实现重写的方法return method.invoke(object, args);}
}
测试
public static void main(String[] args) {ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();// 持有具体实现proxyInvocationHandler.setObject(new UserServiceImpl());// 获取代理对象(已实现具体实现的接口并重写接口方法)UserService proxy = (UserService) proxyInvocationHandler.getProxy();// 执行增强业务proxy.selectAll();
}