Spring : how to replace constructor-arg by annotation? [duplicate]

情到浓时终转凉″ 提交于 2019-12-30 02:09:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!