從.properties檔案中獲取配置資料的方法小結
關於讀入.properties配置檔案資料,有很多方法,比如利用ResourceBundle.getString(“”),Property.getProperty(“”).toString(),@Value(“${}”),Environment.get等方法
ResourceBundle
System.setProperty("spring.profiles.active", "dev");//設定classPath下的指定目錄
ResourceBundle rb = ResourceBundle.getBundle(classPath下的相對路徑);//不用加字尾
BASE_URL = rb.getString ("BASE_URL");
很省事不用寫字尾,但是在Junit下時,不知名原因,導致載入不成功,也有可能是是Junit版本低造成的,我試到4.9都沒成功。。
Properties
Properties prop = new Properties();
String realPath =“.properties”//相對絕對路徑都可以,但是要有properties;
String value= prop.getProperty("goopalpayPay_key").toString();
利用這種方法配置環境,在Junit下利用絕對路徑(String dir=System.getProperty(“user.dir”);)也能跑通測試,但是每次切換環境時,修改太麻煩。當時考慮用拋異常的方式切換,但是這是不靠譜的。
PropertyPlaceHolder
Environment
利用
@PropertySource(value=”file:絕對路徑”)或者@PropertySource(value=”classPath:相對路徑”)進行讀取
需要事先EvironmentAware介面,重寫裡面的setEnvironment方法建立Environment物件
@Autowired
Environment env;
在使用的方法中,建立一個ApplicationContext例項,利用他的getEnvironment方法對重寫的setEnvironment賦值,然後用getProperty(“xxx”)方法獲取properties檔案中的資料
@Configuration
@PropertySource(value = "file:E:/dev-chinagpay.properties")
public class Config implements ApplicationListener<ContextRefreshedEvent> ,EnvironmentAware {
@Autowired
private Environment env;
public static void main (String[] args)
{
ApplicationContext ctx = new GenericApplicationContext();
ct.setEnvironment(ctx.getEnvironment());
System.out.println(ct.getProperty("user.dir"));
System.out.println(ct.env);
}
@Override
public void setEnvironment(Environment environment) {
this.env=environment;
}
}
@Value
在applicationContext中配置
這句話的意思是在啟動spring時,掃描dev目錄下所有的.properties檔案,並以key-value的形式存入
在需要使用properties檔案中的預設值時,直接採用
[@Value("${xxx}")
private String xxx;](http://blog.csdn.net/tornadowp/article/details/8049548)
進行值的獲取與使用