春季:如何更换构造 - 精氨酸通过注释? [英] Spring : how to replace constructor-arg by annotation?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/4614349/replace-constructor-arg-with-spring-annotation\">replace &LT;构造带参数&GT;与Spring注释
我想通过注解来代替一个XML的应用程序配置。
i would like to replace an XML applicationContext configuration by an annotation.
如何与固定构造函数参数代替简单的bean?
How to replace a simple bean with constructor arguments which are fixed ?
例:
<bean id="myBean" class="test.MyBean">
<constructor-arg index="0" value="$MYDIR/myfile.xml"/>
<constructor-arg index="1" value="$MYDIR/myfile.xsd"/>
</bean>
我在阅读一些@Value解释,但我真的不知道如何通过一些固定的值...
I'm reading some explanation on @Value, but i don't really understand how to pass some fixed values...
时可以装入这个bean时,部署Web应用程序?
Is it possible to load this bean when the web application is deployed ?
感谢您。
推荐答案
我觉得你以后有什么是这样的:
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
}
您可能还需要这些文件是通过系统属性配置。您可以使用 @Value
标注用来读取系统属性 PropertyPlaceholderConfigurer
和 $ {}
语法。
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
标注使用不同的字符串
值:
To do this, you can use different String
values in your @Value
annotation:
@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
这篇关于春季:如何更换构造 - 精氨酸通过注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!