spring 如何使用注释向 bean 构造函数注入值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4203302/
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
How to inject a value to bean constructor using annotations
提问by tbruyelle
My spring bean have a constructor with an unique mandatory argument, and I managed to initialize it with the xml configuration :
我的 spring bean 有一个带有唯一强制参数的构造函数,我设法用 xml 配置初始化它:
<bean name="interfaceParameters#ota" class="com.company.core.DefaultInterfaceParameters">
<constructor-arg>
<value>OTA</value>
</constructor-arg>
</bean>
Then I use this bean like this and it works well.
然后我像这样使用这个 bean,它运行良好。
@Resource(name = "interfaceParameters#ota")
private InterfaceParameters interfaceParameters;
But I would like to specify the contructor arg value with the annocations, something like
但我想用注释指定构造函数 arg 值,例如
@Resource(name = "interfaceParameters#ota")
@contructorArg("ota") // I know it doesn't exists!
private InterfaceParameters interfaceParameters;
Is this possible ?
这可能吗 ?
Thanks in advance
提前致谢
回答by Bozho
First, you have to specify the constructor arg in your bean definition, and not in your injection points. Then, you can utilize spring's @Valueannotation (spring 3.0)
首先,您必须在 bean 定义中指定构造函数 arg,而不是在注入点中。然后,您可以使用 spring 的@Value注释(spring 3.0)
@Component
public class DefaultInterfaceParameters {
@Inject
public DefaultInterfaceParameters(@Value("${some.property}") String value) {
// assign to a field.
}
}
This is also encouraged as Spring advises constructor injection over field injection.
这也受到鼓励,因为 Spring 建议构造函数注入而不是字段注入。
As far as I see the problem, this might not suit you, since you appear to define multiple beans of the same class, named differently. For that you cannot use annotations, you have to define these in XML.
就我所看到的问题而言,这可能不适合您,因为您似乎定义了同一个类的多个 bean,名称不同。为此,您不能使用注释,您必须在 XML 中定义它们。
However I do not think it is such a good idea to have these different beans. You'd better use only the string values. But I cannot give more information, because I dont know your exact classes.
然而,我认为拥有这些不同的豆子不是一个好主意。你最好只使用字符串值。但是我不能提供更多信息,因为我不知道您的确切课程。
回答by tapasvi
As Bozho said, instead of constructor arg you could set the property...@PostConstruct will only get called after all the properties are set...so, you will still have your string available ...
正如 Bozho 所说,您可以设置属性而不是构造函数 arg...@PostConstruct 只会在设置所有属性后被调用...因此,您仍然可以使用您的字符串...

