@Value - 永远为null

时间:2015-11-19 10:32:04

标签: java spring null config

我使用@Value注释从属性文件中为变量赋值。

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

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

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

    //Code 
}

该课程使用@Configuration进行注释,并且已初始化'通过web.xml,还设置了环境文件的目录。

<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>

启动时,所有值都为&#39; null&#39;。有什么我想念的吗?

2 个答案:

答案 0 :(得分:2)

我认为您必须将此bean添加到context.xml以从配置文件加载您的属性:

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

然后您需要将context.xml导入您的配置:

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

答案 1 :(得分:2)

您需要配置PropertySourcesPlaceholderConfigurer并指定其位置:

@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();
        }

}