不推荐使用@Autowired 进行Field注入的原因

今天写Spring项目的时候发现,在@Autowired上出现了一个警告

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 }

}

既然提示警告了,说明这种写法肯定存在利弊关系,立马上Google找原因,最后总结如下:

@AutoWired三种注入的方式

一共有三种:分别是( Field-based Injection(属性注入),Setter-based Injection(set方法注入),Constructor-base Injection(构造器注入))

Constructor-base Injection(构造器注入)

public class DI {
    private DependencyA dependencyA;
    private DependencyB dependencyB;
    private DependencyC dependencyC;
​
    @Autowired
    public DI(DependencyA dependencyA, DependencyB dependencyB, DependencyC dependen
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值