问题
Possible Duplicate:
replace <constructor-arg> with Spring Annotation
i would like to replace an XML applicationContext configuration by an annotation.
How to replace a simple bean with constructor arguments which are fixed ?
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...
Is it possible to load this bean when the web application is deployed ?
Thank you.
回答1:
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.
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
来源:https://stackoverflow.com/questions/13725165/spring-how-to-replace-constructor-arg-by-annotation