问题描述:在静态方法中调用本类的另一个静态方法,需要在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 ;
}
}