Convert Spring field injection to constructor injection (IntelliJ IDEA)? Convert Spring field injection to constructor injection (IntelliJ IDEA)? spring spring

Convert Spring field injection to constructor injection (IntelliJ IDEA)?


Yes, it's now implemented in IntelliJ IDEA.

1) Place your cursor on one of the @Autowired annotation.

2) Hit Alt+Enter.

3) Select Create constructor

enter image description here

This is the quick fix related to the inspection "Field injection warning":

Spring Team recommends: "Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies".

Field injection/NullPointerException example:

class MyComponent {  @Inject MyCollaborator collaborator;  public void myBusinessMethod() {    collaborator.doSomething(); // -> NullPointerException     } }   

Constructor injection should be used:

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(); // -> safe     }}


Nothing out of the box.

The way I do is, I do a search and replace for
@Autowired private to @Autowired private final.

Then there is a error displayed saying, final fields are not initialized.
If you do a autocompletion(Alt+Enter), then it asks if you want to create a contructor, and then you can select the fields and click Enter.

private is just an example. It could be any modifier. Main thing is to make the fields final, So that Idea cries with an error and we can kick in auto completion to generate required constructor