通过JDK的Proxy代理实现对业务类做简单的AOP实现
接口:UserService 包含的方法为切入点,会被代理拦截
类:UserServiceImpl 实现UserService接口
类:UserServiceFactory 工厂模式生成动态代理
类:MyAspect 切面类,实现对切入点的操作
UserService :
public interface UserService {
//切面: 需要被拦截的方法
public void addUser();
public void updateUser();
public int deleteUser(int id);
}
UserServiceImpl :
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("UserServiceImpl.add()");
}
public void add(User user) {
System.out.println("UserServiceImpl.add(" + user + ")");
}
//下面继承自UserService接口的方法会被拦截
@Override
public void addUser() {
System.out.println("UserServiceImpl.addUser()");
}
@Override
public void updateUser() {
System.out.println("UserServiceImpl.updateUser()");
}
@Override
public int deleteUser(int id) {
System.out.println("UserServiceImpl.deleteUser(" + id + ")");
return 1;
}
}
UserServiceFactory :
public class UserServiceFactory {
public static UserService createUserService() {
//1、创建目标对象target
final UserService userService = new UserServiceImpl();
//2、声明切面类对象
final MyAspect myAspect = new MyAspect();
//3、将切面类before()与after()方法应用到目标类
//3.1、创建JDK代理(返回一个接口)
/*
newProxyInstance(
ClassLoader loader, //类加载器,写当前类
Class<?>[] interfaces, //接口,接口中包含的方法执行时会被拦截
InvocationHandler h) //处理 调用切面类中的处理如:deforre()、after()
*/
UserService serviceProxy = (UserService) Proxy.newProxyInstance(
UserServiceFactory.class.getClassLoader(),
userService.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//开启事务
myAspect.before();
//返回值是调用的业务方法的返回值
Object obj = method.invoke(userService, args);
//提交事务
myAspect.after();
return obj;
}
});
return serviceProxy;
}
}
MyAspect :(就是一些具体操作,如记录日志等)
public class MyAspect {
public void before() {
System.out.println("MyAspect.before()开启事务...");
}
public void after() {
System.out.println("MyAspect.after()提交事务...");
}
}
单元测试:
@Test
public void aop_test() {
UserService userService = UserServiceFactory.createUserService();
userService.addUser();
userService.deleteUser(10);
userService.updateUser();
}
输出;
MyAspect.before()开启事务...
UserServiceImpl.addUser()
MyAspect.after()提交事务...
MyAspect.before()开启事务...
UserServiceImpl.deleteUser(10)
MyAspect.after()提交事务...
MyAspect.before()开启事务...
UserServiceImpl.updateUser()
MyAspect.after()提交事务...