IDEA 使用@Autowired提示Field injection is not recommended

摘要:IDEA 使用@Autowired提示Field injection is not recommended问题的解决办法。

  在使用@Autowired注解进行bean注入,完成自动装配的工作时,IDEA经常会警告Field injection is not recommended。点击查看警告详细:Spring Team recommends : “Always use constuctor based dependency injection in your beans ,Always use assertions for mandatory dependencies”。这句话的意思是Spring团队建议:“在对bean进行依赖注入时,请始终使用构造器注入方式,始终对强制依赖项使用断言”。

  但是构造器注入方式就是因为代码不够简洁才被我们弃之不用的,而且用属性注入时,代码位一直运行正常。所以,我们可以忽略这个warning黄牌警告,其解决办法有如下两个:

将@Autowired注解替换为@Resource注解

  注解@Resource是先根据Bean的名称去匹配Bean,若获取不到,则根据类型去匹配。而注解@Autowired则是根据类型匹配,若想通过名称匹配,则需要借助Spring的@Qualifier注解。

不检查属性注入

  IntelliJ IDEA 版本2021.3.1 (Ultimate Edition)。修改IDEA中Settings或者Performances里面,对属性注入的检查,依次找到:Performances->editor->code style->inspection-> Spring | Spring Core | Code | Non recommended 'field' injections,去掉钩即可,如下图所示:


不检查属性注入
posted @ 2022-04-16 20:10  楼兰胡杨  阅读(272)  评论(0编辑  收藏  举报