java 我应该为@Autowired 提供一个 setter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4147519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:01:49  来源:igfitidea点击:

Should I provide a setter for @Autowired

javaspring

提问by DwB

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

我在我的项目中使用 Spring 3.0.x。我目前的做法@Autowired举例如下:


 @Autowired
 private SomeType someMemberVariable;

Is the use of a setter method better and/or preferred? By setter, I mean the following:

使用 setter 方法是否更好和/或更受欢迎?通过 setter,我的意思是:


 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.

我理解可变和不可变的 setter,这超出了这个问题的范围。

回答by Kaleb Brasee

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

我更喜欢使用 setter 和 getter,因为当您不在 Spring 上下文中运行它时,它允许您手动连接对象(即,在单元测试中设置模拟)。

回答by Bozho

I'm not using a setter when using @Autowired- it adds boilerplate code.

我在使用时没有使用 setter @Autowired- 它添加了样板代码。

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.

每当我需要在单元测试中设置依赖项时,我都会使用ReflectionTestUtils.setField(..)- 它作为设置器在编译时不是安全的,但我没有遇到太多麻烦。

As a sidenote, if using spring 3.0, you can start using @Injectinstead of @Autowired

作为旁注,如果使用 spring 3.0,您可以开始使用@Inject而不是@Autowired