关于静态代理和动态代理
首先用代码演示一个简单的静态代理实现,程序猿认为代码是最有说服力的。
本例都是基于JDK的动态代理,有关cglib的代理,这里没有介绍,不过大同小异。
一.静态代理
1.首先创建一个实体类:User
public class User {
private String username;
private String email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2.定义一个接口IUserDAO
class UserDAODynProxyTest {public static void main(String args[]) {User user = new User();String username = "";UserDAODynamicProxy userDAODynamicProxy = new UserDAODynamicProxy();IUserDAO userDAO = (IUserDAO) userDAODynamicProxy.bind(new UserDAO());// 绑定代理目标userDAO.saveUser(user);userDAO.findUserByUsername(username);}}