@PropertySouce是spring3.1開始引入的基於java config的註解
通過@PropertySource註解將properties配置文件中的值存儲到Spring的 Environment中,Environment接口提供方法去讀取配置文件中的值,參數是properties文件中定義的key值。
clearLshjTask.properties文件如下:
jobs.schedule = */5 * * * * ?
package com.chen.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:config/clearLshjTask.properties")
public class PropertiesConfig {
@Value("${jobs.schedule}")
private String corn;
public String getCorn() {
return corn;
}
//要想使用@Value 用${}佔位符注入屬性,這個bean是必須的,這個就是佔位bean,另一種方式是不用value直接用Envirment變量直接getProperty('key')
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
我主要解釋一下${jobs.schedule}這個,因爲我已開始接觸@PropertiesSource註解和${}佔位符時繞了很多彎。有的人${}的值沒有注入。你只需要將
//要想使用@Value 用${}佔位符注入屬性,這個bean是必須的,這個就是佔位bean,另一種方式是不用value直接用Envirment變量直接getProperty('key')
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
這個代碼放入其中,你的${}就可以讀取出值了。