SpringBoot下使用AspectJ(CTW)下不能注入SpringIOC容器中的Bean

SpringBoot下使用AspectJ(CTW)下不能注入SpringIOC容器中的Bean

在SpringBoot中开发AspectJ时,使用CTW的方式来织入代码,由于采用这种形式,切面Bean不在SpringIOC容器中,相关的代码在编译时就已经织入目标代码中,而SpringIOC中的Bean在运行期才会被注入。
切面:

    @Autowired
    public LoginService loginService;

    @Pointcut("execution(* com.zakary.qingblog.controller.LoginController.userLogin(..))")
    public void loginAuthority() { }

    @Before("loginAuthority()")
    public void loginAuthority(JoinPoint point) throws Throwable{
        Object[] objArgs = point.getArgs();
        String mail= AnalysisUtils.getObjectToMap(objArgs[0]).get("userMail").toString();
        User user=loginService.getUserInfo(mail);
        int userState=user.getUserState();
        if(userState==3){
            throw new BusinessException("此账户已被注销!");
        }
    }

此时在运行时会发报错,loginService为null,不能通过@Autowired注入
解决:
添加一个配置类

@Configuration
@ComponentScan("com.zakary.qingblog.controller")
public class CustomConfig{

    @Bean
    public AuthorityAspect authorityAspect(){
        AuthorityAspect authorityAspect= Aspects.aspectOf(AuthorityAspect.class);
        return authorityAspect;
    }

}

@ComponentScan 的作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中.
通过@Bean下的方法就可以在切面中注入Spring容器中的Bean了。
可能遇到得问题:
org.aspectj.lang.NoAspectBoundException: Exception while initializing
Bean初始化出错,并提示AspectOf方法缺失
解决方法
(1)因为使用CTW方式,所以需要使用ajc编译器来编译整个项目
Setting->Java Complier->Complier->Ajc
(2)如还存在以上问题,ReBuild项目即可
参考地址1
参考地址2
参考地址3

上一篇:=====关于swing的一些收集-swing大收集======


下一篇:springioc容器创建过程