@Value - 始终为空

@Value - always null

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

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

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

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

    //Code 
}

class注释为@Configuration,通过web.xml注释为'initialized',其中还设置了环境文件的目录。

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

启动时所有值都是 'null'。有什么我想念的吗?

我认为您必须将此 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 {

您需要配置一个 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();
        }

}