I'm using Spring 3.0.x with my project.
My current practice with @Autowired
is exemplified as follows:
@Autowired
private SomeType someMemberVariable;
Is the use of a setter method better and/or preferred? By setter, I mean the following:
private SomeType someMemberVariable;
@Autowired
private void setSomeMemberVariable(SomeType newValue)
{
someMemberVariable = newValue;
}
I understand mutable vs immutable setters, that is out of scope for this question.
You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.
You should use the constructor approach, when you want to create a new instance of the object, with the values already populated(a ready to use object with value populated). This way you need not explicitly call the setter methods for each field in the object to populate them.
I would generally NOT use @Autowired for private fields or methods. @Autowired means, somebody from outside will set this field. "Private" on the other hand means nobody except this class is allowed to use it.
Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will. Typical example, consider having a dateOfBirth parameter.
I'm not using a setter when using @Autowired
- it adds boilerplate code.
Whenever I need to set a dependency in a unit test, I use ReflectionTestUtils.setField(..)
- it is not compile-time safe as a setter, but I haven't got much trouble with it.
As a sidenote, if using spring 3.0, you can start using @Inject
instead of @Autowired
I prefer using setters and getters because it allows you to manually wire up the object when you're not running it in a Spring context (i.e., setting mocks in a unit test).
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