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.
Conclusion. Constructor injection makes code more robust. It allows us to create immutable objects, preventing NullPointerExceptions and other errors..
Constructor injection makes code more robust. It allows us to create immutable objects, preventing NullPointerException s and other errors. You can find the code example on GitHub.
Constructor-based DI fixes the order in which the dependencies need to be injected. Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time. Spring code generation library doesn't support constructor injection so it will not be able to create proxy.
The Setter Injection than Field Injection , most are the same, but because of better testability, so when you use @Autowired when recommended Setter Injection way, so that IDEA will not be given a warning. At the same time, it also reflects the important position of testability!
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
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With