Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I provide a setter for @Autowired

Tags:

java

spring

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.

like image 441
DwB Avatar asked Nov 10 '10 18:11

DwB


People also ask

Is Autowired required for setter injection?

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.

Should I use constructor or setters?

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.

Should Autowired fields be private?

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.

Should you always have getters and setters?

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.


2 Answers

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

like image 70
Bozho Avatar answered Oct 27 '22 01:10

Bozho


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).

like image 44
Kaleb Brasee Avatar answered Oct 27 '22 00:10

Kaleb Brasee