可能重复:
用Spring Annotation替换<constructor-arg>
我想通过注释替换XML applicationContext配置。
如何用修复的构造函数参数替换一个简单的bean?
例子:
<bean id="myBean" class="test.MyBean">
<constructor-arg index="0" value="$MYDIR/myfile.xml"/>
<constructor-arg index="1" value="$MYDIR/myfile.xsd"/>
</bean>
我正在阅读关于@Value的一些解释,但我真的不明白如何传递一些固定值......
部署Web应用程序时是否可以加载此bean?
谢谢。
我想你所追求的是:
@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
,和 ${}
句法。
为此,您可以使用不同的 String
你的价值观 @Value
注解:
@Value("${my.xml.file.property}")
@Value("${my.xsd.file.property}")
但您还需要在系统属性中使用这些属性:
my.xml.file.property=$MYDIR/myfile.xml
my.xsd.file.property=$MYDIR/myfile.xsd
我想你所追求的是:
@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
,和 ${}
句法。
为此,您可以使用不同的 String
你的价值观 @Value
注解:
@Value("${my.xml.file.property}")
@Value("${my.xsd.file.property}")
但您还需要在系统属性中使用这些属性:
my.xml.file.property=$MYDIR/myfile.xml
my.xsd.file.property=$MYDIR/myfile.xsd