Reputation: 1941
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
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
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