开发者

Should I provide a setter for @Autowired

开发者 https://www.devze.com 2023-01-24 16:14 出处:网络
I\'m using Spring 3.0.x with my project. My current practice with @Autowired is exemplified as follows:

I'm using Spring 3.0.x with my project. My current practice with @Autowired is exemplified as follows:


 @Autowi开发者_高级运维red
 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消