suraha
suraha

Reputation: 387

how can i access properties file filed using applicationcontext.xml file in spring?

i added following in my applicationContext File

        <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
            <property name="locations">
                <list>
                    <value>classpath:stage.properties</value>
                    <value>classpath:environment.properties</value>
                </list>
            </property>
        </bean>

where i need to access stage.properties file values .stage.properties file is in src/main/resources

i have written following line in my java class to access this file

         @Value("${spring.username}")
         private String usr;

but i am getting valu for usr is like =${spring.username} what i am missing here?

Upvotes: 1

Views: 2496

Answers (1)

ekem chitsiga
ekem chitsiga

Reputation: 5753

@Value("${spring.username}") notation requires the use of PropertyPalceholderConfigurer / PropertySourcesPlaceholderConfigurer depending on Spring version to resolve property placeholder. Either

Solution 1

Replace

<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
            <property name="locations">
                <list>
                    <value>classpath:stage.properties</value>
                    <value>classpath:environment.properties</value>
                </list>
            </property>
        </bean>

with

<context:property-placeholder location="classpath:stage.propertes,classpath:environment.properties"/>

Make sure to import the Spring context namespace

Solution 2.

Use SpEL to access your properties bean with @Value as follows

@Value("#{properties['spring.username']}
private String usr;

This will access the spring.username property of the properties bean in your context

Upvotes: 2

Related Questions