动态代理:代理就是被代理者没有能力或者不愿意去完成某件事情,需要找个人代替自己去完成这件事,动态代理就是用来对业务功能(方法)进行代理的。
步骤:
1.必须有接口,实现类要实现接口(代理通常是基于接口实现的)。
2.创建一个实现类的对象,该对象为业务对象,紧接着为业务对象做一个代理对象。
案例:在不改变原有代码上,添加计时功能-->不修改findAllUser代码添加计时功能功能。
前序代码(案例准备无实际意义):
public class User {private Integer id;private String username;private String password;public User() {}public User(Integer id, String username, String password) {this.id = id;this.username = username;this.password = password;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +'}';}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}
public interface UserService {//查询所有用户public List<User> findAllUser();}
public class UserServiceImpl implements UserService {@Overridepublic List<User> findAllUser() {//定义集合List<User> userList = new ArrayList<>();//模拟查询数据try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();}userList.add(new User(1,"itheima","123"));userList.add(new User(2,"shheima","123"));userList.add(new User(3,"zhangsan","123456"));userList.add(new User(4,"admin","admin"));return userList;}}
理解,代理(代码):
public class 代理类 {@Testpublic void 方法名(){UserService userService = new UserServiceImpl();//创建: 被代理类对象,多态形式实现/*使用JDK提供Proxy创建代理对象*/UserService proxyObj = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), //参数1:类加载器userService.getClass().getInterfaces(), //参数2:接口数组(被代理类所实现的所有的接口)new InvocationHandler() {public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {long beginTime = System.currentTimeMillis();//记录开始时间Object result = method.invoke( userService , args);//调用被代理的方法long endTime = System.currentTimeMillis();//记录结束时间System.out.println(method.getName()+ "执行消耗:"+(endTime-beginTime)+"毫秒");return result;}});/*使用代理对象,调用方法*/List<User> userList = proxyObj.findAllUser();for (User user : userList) { System.out.println(user);} //测试输出数据}}