Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 833
MychaL Avatar asked Dec 05 '12 14:12

MychaL


1 Answers

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
like image 74
nicholas.hauschild Avatar answered Nov 15 '22 15:11

nicholas.hauschild