java Spring:如何通过注释替换构造函数参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13725165/
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
Spring : how to replace constructor-arg by annotation?
提问by MychaL
Possible Duplicate:
replace <constructor-arg> with Spring Annotation
i would like to replace an XML applicationContext configuration by an annotation.
我想用注释替换 XML applicationContext 配置。
How to replace a simple bean with constructor arguments which are fixed ?
如何用固定的构造函数参数替换简单的 bean?
Exemple :
例子:
<bean id="myBean" class="test.MyBean">
<constructor-arg index="0" value="$MYDIR/myfile.xml"/>
<constructor-arg index="1" value="$MYDIR/myfile.xsd"/>
</bean>
I'm reading some explanation on @Value, but i don't really understand how to pass some fixed values...
我正在阅读有关@Value 的一些解释,但我真的不明白如何传递一些固定值......
Is it possible to load this bean when the web application is deployed ?
是否可以在部署 Web 应用程序时加载此 bean?
Thank you.
谢谢你。
回答by nicholas.hauschild
I think what you are after is this:
我认为你所追求的是:
@Component
public class MyBean {
private String xmlFile;
private String xsdFile;
@Autowired
public MyBean(@Value("$MYDIR/myfile.xml") final String xmlFile,
@Value("$MYDIR/myfile.xsd") final String xsdFile) {
this.xmlFile = xmlFile;
this.xsdFile = xsdFile;
}
//methods
}
You also might want these files to be configurable via system properties. You can use the @Value
annotation to read system properties using the PropertyPlaceholderConfigurer
, and the ${}
syntax.
您可能还希望通过系统属性来配置这些文件。您可以使用@Value
注释来读取使用PropertyPlaceholderConfigurer
, 和${}
语法的系统属性。
To do this, you can use different String
values in your @Value
annotation:
为此,您可以String
在@Value
注释中使用不同的值:
@Value("${my.xml.file.property}")
@Value("${my.xsd.file.property}")
but you will also need these properties in your system properties:
但您的系统属性中还需要这些属性:
my.xml.file.property=$MYDIR/myfile.xml
my.xsd.file.property=$MYDIR/myfile.xsd