讀取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
}





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM