讀取properties四種方式
前言
在專案開發中經常會用到配置檔案,配置檔案的存在解決了很大一份重複的工作。今天就分享四種在Springboot中獲取配置檔案的方式。
注:前三種測試配置檔案為springboot預設的application.properties
檔案
- #######################方式一#########################
- com.battle.type3=Springboot-@ConfigurationProperties
- com.battle.title3=使用@ConfigurationProperties獲取配置檔案
- #map
- com.battle.login[username]=admin
- com.battle.login[password]=123456
- com.battle.login[callback]=http://www.flyat.cc
- #list
- com.battle.urls[0]=http://ztool.cc
- com.battle.urls[1]=http://ztool.cc/format/js
- com.battle.urls[2]=http://ztool.cc/str2image
- com.battle.urls[3]=http://ztool.cc/json2Entity
- com.battle.urls[4]=http://ztool.cc/ua
- #######################方式二#########################
- com.battle.type=Springboot-@Value
- com.battle.title=使用@Value獲取配置檔案
- #######################方式三#########################
- com.battle.type2=Springboot-Environment
- com.battle.title2=使用Environment獲取配置檔案
一、@ConfigurationProperties方式
自定義配置類:PropertiesConfig.java
- importjava.io.UnsupportedEncodingException;
- importjava.util.ArrayList;
- importjava.util.HashMap;
- importjava.util.List;
- importjava.util.Map;
- importorg.springframework.boot.context.properties.ConfigurationProperties;
- //importorg.springframework.context.annotation.PropertySource;
- importorg.springframework.stereotype.Component;
- /**
- *對應上方配置檔案中的第一段配置
- *@authorbattle
- *@date2017年6月1日下午4:34:18
- *@versionV1.0
- *@sinceJDK:1.7*/
- @Component
- @ConfigurationProperties(prefix="com.zyd")
- //PropertySource預設取application.properties
- //@PropertySource(value="config.properties")
- publicclassPropertiesConfig{
- publicStringtype3;publicStringtitle3;
- publicMap<String,String>login=newHashMap<String,String>();
- publicList<String>urls=newArrayList<>();
- publicStringgetType3(){
- returntype3;
- }
- publicvoidsetType3(Stringtype3){
- this.type3=type3;
- }
- publicStringgetTitle3(){
- try{
- returnnewString(title3.getBytes("ISO-8859-1"),"UTF-8");
- }catch(UnsupportedEncodingExceptione){
- e.printStackTrace();
- }
- returntitle3;
- }
- publicvoidsetTitle3(Stringtitle3){
- this.title3=title3;
- }
- publicMap<String,String>getLogin(){returnlogin;}
- publicvoidsetLogin(Map<String,String>login){this.login=login;}
- publicList<String>getUrls(){returnurls;}
- publicvoidsetUrls(List<String>urls){this.urls=urls;}}
程式啟動類:Applaction.java
[java]view plaincopy- importjava.io.UnsupportedEncodingException;
- importjava.util.HashMap;
- importjava.util.Map;
- importorg.springframework.beans.factory.annotation.Autowired;
- importorg.springframework.boot.SpringApplication;
- importorg.springframework.boot.autoconfigure.SpringBootApplication;
- importorg.springframework.web.bind.annotation.RequestMapping;
- importorg.springframework.web.bind.annotation.RestController;
- importcom.zyd.property.config.PropertiesConfig;
- @SpringBootApplication
- @RestController
- publicclassApplaction{
- @AutowiredprivatePropertiesConfigpropertiesConfig;
- /**
- *第一種方式:使用`@ConfigurationProperties`註解將配置檔案屬性注入到配置物件類中
- *@throwsUnsupportedEncodingException
- *@sinceJDK1.7*/
- @RequestMapping("/config")publicMap<String,Object>configurationProperties()
- {
- Map<String,Object>map=newHashMap<String,Object>();
- map.put("type",propertiesConfig.getType3());
- map.put("title",propertiesConfig.getTitle3());
- map.put("login",propertiesConfig.getLogin());
- map.put("urls",propertiesConfig.getUrls());
- return(map);
- }
- publicstaticvoidmain(String[]args)throwsException
- {
- SpringApplicationapplication=newSpringApplication(Applaction.class);
- application.run(args);
- }
- }
訪問結果:
{"title":"使用@ConfigurationProperties獲取配置檔案",
"urls":["http://ztool.cc","http://ztool.cc/format/js","http://ztool.cc/str2image",
"http://ztool.cc/json2Entity","http://ztool.cc/ua"],
"login":{"username":"admin",
"callback":"http://www.flyat.cc","password":"123456"},
"type":"Springboot - @ConfigurationProperties"}
二、使用@Value註解方式
程式啟動類:Applaction.java
- importjava.io.UnsupportedEncodingException;
- importjava.util.HashMap;
- importjava.util.Map;
- importorg.springframework.beans.factory.annotation.Value;
- importorg.springframework.boot.SpringApplication;
- importorg.springframework.boot.autoconfigure.SpringBootApplication;
- importorg.springframework.web.bind.annotation.RequestMapping;
- importorg.springframework.web.bind.annotation.RestController;
- @SpringBootApplication
- @RestController
- publicclassApplaction{
- @Value("${com.zyd.type}")privateStringtype;
- @Value("${com.zyd.title}")privateStringtitle;
- /****第二種方式:使用`@Value("${propertyName}")`註解*
- *@throwsUnsupportedEncodingException*@sinceJDK1.7*/
- @RequestMapping("/value")publicMap<String,Object>value()throwsUnsupportedEncodingException{
- Map<String,Object>map=newHashMap<String,Object>();
- map.put("type",type);
- //*.properties檔案中的中文預設以ISO-8859-1方式編碼,因此需要對中文內容進行重新編碼
- map.put("title",newString(title.getBytes("ISO-8859-1"),"UTF-8"));
- returnmap;
- }
- publicstaticvoidmain(String[]args)throwsException{
- SpringApplicationapplication=newSpringApplication(Applaction.class);
- application.run(args);
- }}
訪問結果:
{"title":"使用@Value獲取配置檔案","type":"Springboot - @Value"}
三、使用Environment
程式啟動類:Applaction.java
- importjava.io.UnsupportedEncodingException;
- importjava.util.HashMap;
- importjava.util.Map;
- importorg.springframework.beans.factory.annotation.Autowired;
- importorg.springframework.boot.SpringApplication;
- importorg.springframework.boot.autoconfigure.SpringBootApplication;
- importorg.springframework.core.env.Environment;
- importorg.springframework.web.bind.annotation.RequestMapping;
- importorg.springframework.web.bind.annotation.RestController;
- @SpringBootApplication
- @RestController
- publicclassApplaction{
- @AutowiredprivateEnvironmentenv;
- /****第三種方式:使用`Environment`**@authorzyd*@throwsUnsupportedEncodingException*@sinceJDK1.7*/
- @RequestMapping("/env")publicMap<String,Object>env()throwsUnsupportedEncodingException{
- Map<String,Object>map=newHashMap<String,Object>();
- map.put("type",env.getProperty("com.zyd.type2"));
- map.put("title",newString(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"),"UTF-8"));
- returnmap;
- }
- publicstaticvoidmain(String[]args)throwsException{
- SpringApplicationapplication=newSpringApplication(Applaction.class);
- application.run(args);
- }
- }
訪問結果:
{"title":"使用Environment獲取配置檔案","type":"Springboot - Environment"}
四、使用PropertiesLoaderUtils
app-config.properties
- ####通過註冊監聽器(`Listeners`)+`PropertiesLoaderUtils`的方式
- com.battle.type=Springboot-Listeners
- com.battle.title=使用Listeners+PropertiesLoaderUtils獲取配置檔案
- com.battle.name=zyd
- com.battle.address=Beijing
- com.battle.company=in
PropertiesListener.java 用來初始化載入配置檔案
- importorg.springframework.boot.context.event.ApplicationStartedEvent;
- importorg.springframework.context.ApplicationListener;
- importcom.zyd.property.config.PropertiesListenerConfig;
- publicclassPropertiesListenerimplementsApplicationListener<ApplicationStartedEvent>{
- privateStringpropertyFileName;
- publicPropertiesListener(StringpropertyFileName){
- this.propertyFileName=propertyFileName;
- }
- @OverridepublicvoidonApplicationEvent(ApplicationStartedEventevent){
- PropertiesListenerConfig.loadAllProperties(propertyFileName);
- }
- }
PropertiesListenerConfig.java 載入配置檔案內容
[java]view plaincopy- importorg.springframework.boot.context.event.ApplicationStartedEvent;
- importorg.springframework.context.ApplicationListener;
- importcom.zyd.property.config.PropertiesListenerConfig;
- publicclassPropertiesListenerimplementsApplicationListener<ApplicationStartedEvent>{
- privateStringpropertyFileName;
- publicPropertiesListener(StringpropertyFileName){
- this.propertyFileName=propertyFileName;
- }
- @OverridepublicvoidonApplicationEvent(ApplicationStartedEventevent){
- PropertiesListenerConfig.loadAllProperties(propertyFileName);
- }
- }
Applaction.java 啟動類
[java]view plaincopy- importjava.io.UnsupportedEncodingException;
- importjava.util.HashMap;
- importjava.util.Map;
- importorg.springframework.boot.SpringApplication;
- importorg.springframework.boot.autoconfigure.SpringBootApplication;
- importorg.springframework.web.bind.annotation.RequestMapping;
- importorg.springframework.web.bind.annotation.RestController;
- importcom.zyd.property.config.PropertiesListenerConfig;
- importcom.zyd.property.listener.PropertiesListener;
- @SpringBootApplication@RestControllerpublicclassApplaction{
- /****第四種方式:通過註冊監聽器(`Listeners`)+`PropertiesLoaderUtils`的方式**@authorzyd*@throwsUnsupportedEncodingException*@sinceJDK1.7*/
- @RequestMapping("/listener")publicMap<String,Object>listener(){
- Map<String,Object>map=newHashMap<String,Object>();
- map.putAll(PropertiesListenerConfig.getAllProperty());
- returnmap;
- }
- publicstaticvoidmain(String[]args)throwsException{
- SpringApplicationapplication=newSpringApplication(Applaction.class);
- //第四種方式:註冊監聽器application.addListeners(newPropertiesListener("app-config.properties"));application.run(args);}}
訪問結果:
[java]view plaincopy- {"com.battle.name":"zyd",
- "com.battle.address":"Beijing",
- "com.battle.title":"使用Listeners+PropertiesLoaderUtils獲取配置檔案",
- "com.battle.type":"Springboot-Listeners",
- "com.battle.company":"in"}