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

cellepo :

I am convinced to convert my Spring Java field injection [@Autowired] to constructor injection (among other reasons, to facilitate mock unit testing)...

Is there a utility I can use to automatically do that Spring field to constructor injection conversion?

For example, IntelliJ IDEA has generation shortcuts for a lot of things (i.e: generate setters & getters for fields); I'm hoping there's something similar to that... This is particularly useful when it is tedious to do the conversion manually, because a class to be converted already has numerous field-injected fields.

Ortomala Lokni :

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   
  }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460057&siteId=1