public interface UserService {
void addUser();
void updateUser(String str);
}
UserServiceImpl实现类
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("添加用户");
}
@Override
public void updateUser(String str) {
System.out.println("更新用户信息" + str);
}
}
UserProxy代理类,实现InvocationHandler接口重写invoke方法
public class UserProxy implements InvocationHandler {
private Object target;
public UserProxy(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object res = method.invoke(target, args);
System.out.println("记录日志");
return res;
}
}
test测试类
public class test {
public static void main(String[] args) {
UserServiceImpl impl = new UserServiceImpl();
UserProxy userProxy = new UserProxy(impl);
UserService userService = (UserService) Proxy.newProxyInstance(impl.getClass().getClassLoader(),impl.getClass().getInterfaces(),userProxy);
userService.addUser();
userService.updateUser(":我是皮皮虾");
}
}
public class UserServiceImpl {
public void addUser() {
System.out.println("添加了一个用户");
}
public void deleteUser() {
System.out.println("删除了一个用户");
}
}
UserServiceCGlib代理
public class UserServiceCGlib implements MethodInterceptor {
private Object target;
public UserServiceCGlib() {
}
public UserServiceCGlib(Object target) {
this.target = target;
}
//返回一个代理对象: 是 target对象的代理对象
public Object getProxyInstance() {
//1. 创建一个工具类
Enhancer enhancer = new Enhancer();
//2. 设置父类
enhancer.setSuperclass(target.getClass());
//3. 设置回调函数
enhancer.setCallback(this);
//4. 创建子类对象,即代理对象
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("增强开始~~~");
Object result = methodProxy.invokeSuper(o, objects);
System.out.println("增强结束~~~");
return result;
}
}
test测试类
public class test {
public static void main(String[] args) {
UserServiceCGlib serviceCGlib = new UserServiceCGlib(new UserServiceImpl());
UserServiceImpl userService = (UserServiceImpl)serviceCGlib.getProxyInstance();
userService.addUser();
System.out.println();
userService.deleteUser();
}
}