Springboot配置AOP的注解切点失效解决方案
作者:sheclockes
本文探讨了在Spring框架中使用AOP拦截静态方法调用的实现细节,重点在于ApplicationContext和ApplicationContextAware接口的使用差异,通过对比两种获取Bean的方式,最终解决了切点无法被拦截的问题
问题描述
在静态方法中调用本类的另一个静态方法,需要在AOP中拦截该方法实现一部分业务逻辑,在aop类中添加了@Aspect@Component@EnableAspectJAutoProxy三个注解,切点通知方式为@Around,但是切点一直无法被拦截。
问题发现
当前类的实例是通过applicaitoncontext.getBean(类名.class)获取的,所以一直无法在切点无法被拦截(代码中的第一种方式)。
修改为实现了ApplicationContextAware接口的getBean(类名.class)(代码中的第二种方式),就可以正常被拦截了。
applicaitoncontext和ApplicationContextAware的getBaen()方法的异同点查询文档可知:
当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。
换句话说:
就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getBean(Class<T> tClass){
return applicationContext.getBean(tClass);
}
public static <T> T getBean(String name , Class<T> tClass){
return applicationContext.getBean(name,tClass);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtils.applicationContext = applicationContext;
}
}@Component
public class SendSmm {
private static SendSmm sendSmm=null;
public static void test1(){
if(null == sendSmm){
sendSmm = Const.applicationContext.getBean(SendSmm.class);//第一种
sendSmm = ApplicationContextUtils.getBean(SendSmm.class);//第二种
}
sendSmm.test2();
}
public void test2(){
}
}public class Const {
public static ApplicationContext applicationContext = null ;
}@Aspect
@Component
@EnableAspectJAutoProxy
public class TestAopUtils {
@Pointcut("execution( public * com.example.demo.service.*(..))")
public void testAop(){}
@Around("testAop()")
public Object Around (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object object = null;
Object[] args = proceedingJoinPoint.getArgs();//获取切点的请求参数
String st = (String) args[0];//第一个参数
proceedingJoinPoint.proceed();//调用原方法
return object ;
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
