I see many Java examples using dependency injection with private fields without a public setter like this:
public SomeClass {
@Inject
private SomeResource resource;
}
But that is a bad idea when the injection should be performed manually for example in unit tests.
There are several possibilities to solve this:
setSomeResource(SomeResource r)
I'd like to avoid the setter, since nothing really happens in it. So I'd prefer public or package protected. What do you recommend?
Field Injection uses reflection to set the values of private variables. Constructor Injection happens at the time of creating the object itself. Setter Injection uses setters to set the value.
Use Setter injection when a number of dependencies are more or you need readability. Use Constructor Injection when Object must be created with all of its dependency.
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.
One way to avoid creating a setter for the field is using constructor injection. This even allows you to declare the field as final.
It goes like this:
public class SomeClass {
private final SomeResource resource;
@Inject
public SomeClass(SomeResource resource) {
this.resource = resource;
}
}
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