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