今天写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