user16655
user16655

Reputation: 1941

@Value - always null

I'm using the @Value annotation to assign variables a value from the properties file.

@Configuration
public class AppConfig {
    @Value("${db.url}")
    private String url;

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

    @Value("${db.password}")
    private String password;

    //Code 
}

The class is annotated with @Configuration, and is 'initialized' via web.xml, where the directory for the environment file is also set.

<context-param>
    <param-name>envir.dir</param-name>
    <param-value>/path/to/environment/variables/</param-value>
</context-param>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>eu.nets.bankid.sdm.AppConfig</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

On startup all the values are 'null'. Is there something I'm missing?

Upvotes: 1

Views: 1385

Answers (2)

Rafik BELDI
Rafik BELDI

Reputation: 4158

you need to configure a PropertySourcesPlaceholderConfigurer and specify its location:

@Configuration   
@PropertySource("file:#{contextParameters.envi.dir}/application.properties")//location of your property file
public class AppConfig {

        @Value("${db.url}")
        private String url;

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

        @Value("${db.password}")
        private String password;

        //other bean configuration
        //..
        @Bean
        static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }

}

Upvotes: 2

nogard
nogard

Reputation: 9716

I think you have to add this bean to your context.xml to load your properties from configuration file:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
    <property name="location" value="classpath:server.properties"/>
</bean>

Then you would need to import that context.xml to your configuration:

@Configuration
@ImportResource("classpath:context.xml")
public class AppConfig {

Upvotes: 2

Related Questions