@Autowired提示:Field injection is not recommended

avatar
作者
筋斗云
阅读量:0

1、问题

在这里插入图片描述

在项目升级版本过程中,@Autowired提示Field injection is not recommended 

在这里插入图片描述

 Field injection is not recommended   Inspection info: Reports injected or autowired fields in Spring components. The quick-fix suggests the recommended constructor-based dependency injection in beans and assertions for mandatory fields. Example: class MyComponent {   @Inject MyCollaborator collaborator; // injected field    public void myBusinessMethod() {     collaborator.doSomething(); // throws NullPointerException   } }   After applying the quick-fix: class MyComponent {    private final MyCollaborator collaborator;    @Inject   public MyComponent(MyCollaborator collaborator) {     Assert.notNull(collaborator, "MyCollaborator must not be null!");     this.collaborator = collaborator;   }    public void myBusinessMethod() {     collaborator.doSomething(); // now this call is safe   } } 

2、原因

重点应该在这一句

The quick-fix suggests the recommended constructor-based dependency injection in beans and assertions for mandatory fields. 

其实就是要基于构造函数进行依赖注入,估计有可能会在未来某个版本会删除该用法吧。

3、解决

把 import org.springframework.beans.factory.annotation.Autowired;
替换成
import jakarta.annotation.Resource;

问题解决。

OK,就这些吧。
有什么不对的还望指正,书写不易,觉得有帮助就点个赞吧!☺☺☺

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!