package com.aop;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.lang.Nullable;
import java.lang.reflect.Method;
public class AopTest {
public static void main(String[] args) {
AccountService target = new AccountService("张三", 10000D);
//代理工厂(传入目标对象源,从中可以获取到目标对象)
ProxyFactory proxyFactory = new ProxyFactory(new SingletonTargetSource(target));
//前置通知
proxyFactory.addAdvice(new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, @Nullable Object target) {
System.out.println("【代理对象】开始调用...");
String userName = (String) args[0];
//用户校验
if (!"张三".equals(userName)) {
throw new RuntimeException(String.format("用户%s无权访问!", userName));
}
}
});
//后置通知
proxyFactory.addAdvice(new AfterReturningAdvice() {
@Override
public void afterReturning(@Nullable Object returnValue, Method method, Object[] args, @Nullable Object target) {
System.out.println(method + ",执行完毕!");
System.out.println("【代理对象】结束调用...");
System.out.println();
}
});
// spring aop中最常用的方法拦截器
proxyFactory.addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
log.info("methodInterceptor enter...");
log.info("methodInterceptor:{}", invocation.getMethod());
log.info("methodInterceptor:{}", Arrays.toString(invocation.getArguments()));
log.info("methodInterceptor:{}", invocation.getThis());
log.info("methodInterceptor:{}", invocation.getStaticPart());
Object result = invocation.proceed();
System.out.println("methodInterceptor leave...");
return result;
}
});
//通过代理工厂创建代理
AccountService proxy = (AccountService) proxyFactory.getProxy();
//调用代理的方法
proxy.add("张三", 100);
proxy.reduce("李四", 100);
}
}
手动AOP编程(ProxyFactory使用)
于 2023-01-09 16:02:46 首次发布
该代码示例展示了如何在SpringAOP中使用代理工厂创建代理对象,添加前置通知、后置通知以及方法拦截器。在方法调用前后进行用户校验和日志记录,当调用`add`和`reduce`方法时,根据不同的用户权限执行操作。
摘要由CSDN通过智能技术生成