使用动态代理面向切面编程(AOP)
模型类
User.java
package com.test.model;public class User {private String username;private String password;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;}}
?
接口
UserDAO.java
package com.test.dao;import com.test.model.User;public interface UserDAO {public void save(User user);}
?
实现接口类
UserDAOImpl.java
?
package com.test.dao.impl;import com.test.dao.UserDAO;import com.test.model.User;public class UserDAOImpl implements UserDAO {public void save(User user) {System.out.println("user saved!");}}
?
拦截器
MyInterceptor.java
package com.test.interceptor;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class MyInterceptor implements InvocationHandler {// 被代理对象private Object target;public Object getTarget() {return target;}public void setTarget(Object target) {this.target = target;}public void beforeMethod(Method m) {System.out.println(m.getName() + " start!");}@Overridepublic Object invoke(Object proxy, Method m, Object[] args) throws Throwable {beforeMethod(m);// m方法被"被代理对象"调用m.invoke(target, args);return null;}}
?
Junit测试类
UserServiceTest.java
package com.test.service;import java.lang.reflect.Proxy;import org.junit.Test;import com.test.dao.UserDAO;import com.test.dao.impl.UserDAOImpl;import com.test.interceptor.MyInterceptor;import com.test.model.User;public class UserServiceTest {@Testpublic void testProxy() {// 创建被代理对象UserDAO userDAO = new UserDAOImpl();// 创建拦截器对象MyInterceptor myInterceptor = new MyInterceptor();// 设置被代理对象myInterceptor.setTarget(userDAO);// 产生代理对象// 第一个参数:用哪个ClassLoader来产生代理对象// 第二个参数:产生的代理对象实现了哪些接口,这里也可以用userDAO.getClass().getInterfaces()// 第三个参数:当产生这个代理对象后,调用它里面的方法时,用哪个Handler进行处理UserDAO userDAOProxy = (UserDAO) Proxy.newProxyInstance(userDAO.getClass().getClassLoader(), new Class[] { UserDAO.class }, myInterceptor);System.out.println(userDAOProxy.getClass().getName());//打印的值:$Proxy4,说明它是一个代理对象userDAOProxy.save(new User());}}
?
执行测试方法后,打印:
$Proxy4
save start!
user saved!
?