DwB
DwB

Reputation: 38338

Should I provide a setter for @Autowired

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.

Upvotes: 13

Views: 11270

Answers (2)

Bozho
Bozho

Reputation: 597402

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

Upvotes: 16

Kaleb Brasee
Kaleb Brasee

Reputation: 51965

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

Upvotes: 16

Related Questions