google 搜索 spring aop annotation,看了一大堆,好多过时的内容,要么就特别复杂,再搜中文的 “spring 注解 代理”,看了半天也没啥帮助,今天试着试着突然搞定了,特别简单
springboot 用不着配置文件
定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MapCache {
}
配置后置处理器
@Configuration
public class AopConfig implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String s) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//这个地方不添加过滤会导致 tomcat 启动失败,目前还没定位到确切原因
if (!bean.getClass().getName().startsWith("com.example.wsdemo")) {
return bean;
}
ProxyFactory factory = new ProxyFactory();
factory.setTarget(bean);
factory.addAdvisor(new MapCacheAdvice());
return factory.getProxy();
}
}
MapCacheAdvice
源码
public class MapCacheAdvice extends DefaultPointcutAdvisor {
@Override
public Pointcut getPointcut() {
return new AnnotationMatchingPointcut(null, MapCache.class);
}
@Override
public Advice getAdvice() {
return new MapCacheInterceptor();
}
public static class MapCacheInterceptor implements MethodInterceptor, Advice {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("===========================");
Object result = invocation.proceed();
System.out.println("---------------------------");
return result;
}
}
}
测试
@Service
public class SayService {
@Autowired
BBService bbService;
public String say() {
System.out.println("+++ say +++");
return bbService.getValue() + " hello";
}
@MapCache
public String say(String name) {
System.out.println("+++ say hello +++");
return bbService.getValue() + " hello " \+ name;
}
}
@Controller
public class IndexController {
@ResponseBody
@GetMapping("/test")
public String say() {
sayService.say("pk");
return sayService.say();
}
}
调用结果
===========================
+++ say hello +++
---------------------------
+++ say +++
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于