springproperty-placeholder

@Value in my spring controller does not work


My controller has

@Value("${myProp}")
private String myProp;

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
}

@RequestMapping(value = "myProp", method = RequestMethod.GET)
public @ResponseBody String getMyProp(){
    return "The prop is:" + myProp;
}

my applicationcontext.xml has

<bean id="appConfigProperties" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location" value="classpath:MyApps-local.properties" />
</bean>

I get the following exception:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'myProp' in string value "${myProp}"

Note: My properties file MyApps-local.properties is in the classpath and contains myProp=delightful

any help would be great....


Solution

  • In XML based configuration you need to use PropertyPlaceholderConfigurer bean

    <beans xmlns="http://www.springframework.org/schema/beans" . . . >
      . . .
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:database.properties" />
        </bean>
      . . .
    </beans>
    

    but you can use values from database.properties in xml configuration only

    <beans xmlns="http://www.springframework.org/schema/beans" . . >
      . . .
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
      . . .
    </beans>
    

    If you want to use values from properties files inside @Value annotation for bean's fields, you need to add @Confuguration and @PropertySource annotation to bean class. Like this

    @Configuration
    @PropertySource("classpath:database.properties")
    public class AppConfig {
    
        @Value("${jdbc.url}")
        private String url;
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    }