测试类:
public static void main(String[] args) {
Object proxyedObject = new UserServiceImpl(); // 被代理的对象
ProxyUtil proxyUtils = new ProxyUtil(proxyedObject);
// 生成代理对象,对被代理对象的这些接口进行代理:UserServiceImpl.class.getInterfaces()
UserService proxyObject = (UserService) Proxy.newProxyInstance(Thread
.currentThread().getContextClassLoader(), UserServiceImpl.class
.getInterfaces(), proxyUtils);
proxyObject.getUser(1);
proxyObject.addUser(new User());
}
aop切入
public class ProxyUtil implements InvocationHandler{
private Object target; // 被代理的对象
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("do sth before....");
Object result = method.invoke(target, args);
System.out.println("do sth after....");
return result;
}
ProxyUtil(Object target){
this.target = target;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
public class User {
private int id;
private String name;
private String pwd;
public interface UserService {
public void addUser(User user);
public User getUser(int id);
}
public class UserServiceImpl implements UserService{
public void addUser(User user) {
System.out.println("add User into database.");
}
public User getUser(int id) {
User user = new User();
user.setId(id);
System.out.println("get User from database.");
return user;
}
}
摘抄的,仅做记录,用到时借鉴一下。