读取properties内容到java类@Value取不到值的原因(引用application.properties中自定义的值)

 

<context:property-placeholder location="classpath:config.properties"/>
<!-- 应用属性文件读入 -->
<bean id="applicationProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:*.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="applicationProperties" />
</bean>

 

@Component
public class Test {
@Value("${APP_ID}")
private String appId;
@Value("${API_SERVER_HOST}")
private String apiServerHost;

public String getAppId() {
return appId;
}



public String getApiServerHost() {
return apiServerHost;
}


}

@Autowired
Test test;

在spring mvc架构中,如果希望在程序中直接使用properties中定义的配置值,通常使用一下方式来获取:
@Value("${tag}")
private String tagValue;

但是取值时,有时这个tagvalue为NULL,可能原因有:

1.使用static或final修饰了tagValue,如下:

private static String tagValue; //错误
private final String tagValue; //错误

2.类没有加上@Component(或者@service等)

@Component //遗漏
class TestValue{
    @Value("${tag}")
    private String tagValue;
}

3.类被new新建了实例,而没有使用@Autowired

复制代码
@Component 
class TestValue{
    @Value("${tag}")
    private String tagValue;
}

class Test{
    ...
    TestValue testValue = new TestValue()
}
复制代码

 


正确方式: 上面这个testValue中肯定是取不到值的,必须使用@Autowired:

class Test{
    @AutoWired
    TestValue testValue
}




posted @ 2019-04-02 15:35  菜鸟程序猿朱  阅读(3236)  评论(0编辑  收藏  举报