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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步