@Autowired提示:Field injection is not recommended
创始人
2024-11-04 05:05:55

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,就这些吧。
有什么不对的还望指正,书写不易,觉得有帮助就点个赞吧!☺☺☺

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...