1. 程式人生 > 實用技巧 >讀取properties四種方式

讀取properties四種方式

前言

在專案開發中經常會用到配置檔案,配置檔案的存在解決了很大一份重複的工作。今天就分享四種在Springboot中獲取配置檔案的方式。

注:前三種測試配置檔案為springboot預設的application.properties檔案

[html]view plaincopy
  1. #######################方式一#########################
  2. com.battle.type3=Springboot-@ConfigurationProperties
  3. com.battle.title3=使用@ConfigurationProperties獲取配置檔案
  4. #map
  5. com.battle.login[username]=admin
  6. com.battle.login[password]=123456
  7. com.battle.login[callback]=http://www.flyat.cc
  8. #list
  9. com.battle.urls[0]=http://ztool.cc
  10. com.battle.urls[1]=http://ztool.cc/format/js
  11. com.battle.urls[2]=http://ztool.cc/str2image
  12. com.battle.urls[3]=http://ztool.cc/json2Entity
  13. com.battle.urls[4]=http://ztool.cc/ua
  14. #######################方式二#########################
  15. com.battle.type=Springboot-@Value
  16. com.battle.title=使用@Value獲取配置檔案
  17. #######################方式三#########################
  18. com.battle.type2=Springboot-Environment
  19. com.battle.title2=使用Environment獲取配置檔案

一、@ConfigurationProperties方式

自定義配置類:PropertiesConfig.java

[java]view plaincopy
  1. importjava.io.UnsupportedEncodingException;
  2. importjava.util.ArrayList;
  3. importjava.util.HashMap;
  4. importjava.util.List;
  5. importjava.util.Map;
  6. importorg.springframework.boot.context.properties.ConfigurationProperties;
  7. //importorg.springframework.context.annotation.PropertySource;
  8. importorg.springframework.stereotype.Component;
  9. /**
  10. *對應上方配置檔案中的第一段配置
  11. *@authorbattle
  12. *@date2017年6月1日下午4:34:18
  13. *@versionV1.0
  14. *@sinceJDK:1.7*/
  15. @Component
  16. @ConfigurationProperties(prefix="com.zyd")
  17. //PropertySource預設取application.properties
  18. //@PropertySource(value="config.properties")
  19. publicclassPropertiesConfig{
  20. publicStringtype3;publicStringtitle3;
  21. publicMap<String,String>login=newHashMap<String,String>();
  22. publicList<String>urls=newArrayList<>();
  23. publicStringgetType3(){
  24. returntype3;
  25. }
  26. publicvoidsetType3(Stringtype3){
  27. this.type3=type3;
  28. }
  29. publicStringgetTitle3(){
  30. try{
  31. returnnewString(title3.getBytes("ISO-8859-1"),"UTF-8");
  32. }catch(UnsupportedEncodingExceptione){
  33. e.printStackTrace();
  34. }
  35. returntitle3;
  36. }
  37. publicvoidsetTitle3(Stringtitle3){
  38. this.title3=title3;
  39. }
  40. publicMap<String,String>getLogin(){returnlogin;}
  41. publicvoidsetLogin(Map<String,String>login){this.login=login;}
  42. publicList<String>getUrls(){returnurls;}
  43. publicvoidsetUrls(List<String>urls){this.urls=urls;}}

程式啟動類:Applaction.java

[java]view plaincopy
  1. importjava.io.UnsupportedEncodingException;
  2. importjava.util.HashMap;
  3. importjava.util.Map;
  4. importorg.springframework.beans.factory.annotation.Autowired;
  5. importorg.springframework.boot.SpringApplication;
  6. importorg.springframework.boot.autoconfigure.SpringBootApplication;
  7. importorg.springframework.web.bind.annotation.RequestMapping;
  8. importorg.springframework.web.bind.annotation.RestController;
  9. importcom.zyd.property.config.PropertiesConfig;
  10. @SpringBootApplication
  11. @RestController
  12. publicclassApplaction{
  13. @AutowiredprivatePropertiesConfigpropertiesConfig;
  14. /**
  15. *第一種方式:使用`@ConfigurationProperties`註解將配置檔案屬性注入到配置物件類中
  16. *@throwsUnsupportedEncodingException
  17. *@sinceJDK1.7*/
  18. @RequestMapping("/config")publicMap<String,Object>configurationProperties()
  19. {
  20. Map<String,Object>map=newHashMap<String,Object>();
  21. map.put("type",propertiesConfig.getType3());
  22. map.put("title",propertiesConfig.getTitle3());
  23. map.put("login",propertiesConfig.getLogin());
  24. map.put("urls",propertiesConfig.getUrls());
  25. return(map);
  26. }
  27. publicstaticvoidmain(String[]args)throwsException
  28. {
  29. SpringApplicationapplication=newSpringApplication(Applaction.class);
  30. application.run(args);
  31. }
  32. }



訪問結果:
{"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

[java]view plaincopy
  1. importjava.io.UnsupportedEncodingException;
  2. importjava.util.HashMap;
  3. importjava.util.Map;
  4. importorg.springframework.beans.factory.annotation.Value;
  5. importorg.springframework.boot.SpringApplication;
  6. importorg.springframework.boot.autoconfigure.SpringBootApplication;
  7. importorg.springframework.web.bind.annotation.RequestMapping;
  8. importorg.springframework.web.bind.annotation.RestController;
  9. @SpringBootApplication
  10. @RestController
  11. publicclassApplaction{
  12. @Value("${com.zyd.type}")privateStringtype;
  13. @Value("${com.zyd.title}")privateStringtitle;
  14. /****第二種方式:使用`@Value("${propertyName}")`註解*
  15. *@throwsUnsupportedEncodingException*@sinceJDK1.7*/
  16. @RequestMapping("/value")publicMap<String,Object>value()throwsUnsupportedEncodingException{
  17. Map<String,Object>map=newHashMap<String,Object>();
  18. map.put("type",type);
  19. //*.properties檔案中的中文預設以ISO-8859-1方式編碼,因此需要對中文內容進行重新編碼
  20. map.put("title",newString(title.getBytes("ISO-8859-1"),"UTF-8"));
  21. returnmap;
  22. }
  23. publicstaticvoidmain(String[]args)throwsException{
  24. SpringApplicationapplication=newSpringApplication(Applaction.class);
  25. application.run(args);
  26. }}


訪問結果:
{"title":"使用@Value獲取配置檔案","type":"Springboot - @Value"}

三、使用Environment
程式啟動類:Applaction.java

[java]view plaincopy
  1. importjava.io.UnsupportedEncodingException;
  2. importjava.util.HashMap;
  3. importjava.util.Map;
  4. importorg.springframework.beans.factory.annotation.Autowired;
  5. importorg.springframework.boot.SpringApplication;
  6. importorg.springframework.boot.autoconfigure.SpringBootApplication;
  7. importorg.springframework.core.env.Environment;
  8. importorg.springframework.web.bind.annotation.RequestMapping;
  9. importorg.springframework.web.bind.annotation.RestController;
  10. @SpringBootApplication
  11. @RestController
  12. publicclassApplaction{
  13. @AutowiredprivateEnvironmentenv;
  14. /****第三種方式:使用`Environment`**@authorzyd*@throwsUnsupportedEncodingException*@sinceJDK1.7*/
  15. @RequestMapping("/env")publicMap<String,Object>env()throwsUnsupportedEncodingException{
  16. Map<String,Object>map=newHashMap<String,Object>();
  17. map.put("type",env.getProperty("com.zyd.type2"));
  18. map.put("title",newString(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"),"UTF-8"));
  19. returnmap;
  20. }
  21. publicstaticvoidmain(String[]args)throwsException{
  22. SpringApplicationapplication=newSpringApplication(Applaction.class);
  23. application.run(args);
  24. }
  25. }

訪問結果:
{"title":"使用Environment獲取配置檔案","type":"Springboot - Environment"}
四、使用PropertiesLoaderUtils
app-config.properties

[html]view plaincopy
  1. ####通過註冊監聽器(`Listeners`)+`PropertiesLoaderUtils`的方式
  2. com.battle.type=Springboot-Listeners
  3. com.battle.title=使用Listeners+PropertiesLoaderUtils獲取配置檔案
  4. com.battle.name=zyd
  5. com.battle.address=Beijing
  6. com.battle.company=in

PropertiesListener.java 用來初始化載入配置檔案

[java]view plaincopy
  1. importorg.springframework.boot.context.event.ApplicationStartedEvent;
  2. importorg.springframework.context.ApplicationListener;
  3. importcom.zyd.property.config.PropertiesListenerConfig;
  4. publicclassPropertiesListenerimplementsApplicationListener<ApplicationStartedEvent>{
  5. privateStringpropertyFileName;
  6. publicPropertiesListener(StringpropertyFileName){
  7. this.propertyFileName=propertyFileName;
  8. }
  9. @OverridepublicvoidonApplicationEvent(ApplicationStartedEventevent){
  10. PropertiesListenerConfig.loadAllProperties(propertyFileName);
  11. }
  12. }

PropertiesListenerConfig.java 載入配置檔案內容

[java]view plaincopy
  1. importorg.springframework.boot.context.event.ApplicationStartedEvent;
  2. importorg.springframework.context.ApplicationListener;
  3. importcom.zyd.property.config.PropertiesListenerConfig;
  4. publicclassPropertiesListenerimplementsApplicationListener<ApplicationStartedEvent>{
  5. privateStringpropertyFileName;
  6. publicPropertiesListener(StringpropertyFileName){
  7. this.propertyFileName=propertyFileName;
  8. }
  9. @OverridepublicvoidonApplicationEvent(ApplicationStartedEventevent){
  10. PropertiesListenerConfig.loadAllProperties(propertyFileName);
  11. }
  12. }

Applaction.java 啟動類

[java]view plaincopy
  1. importjava.io.UnsupportedEncodingException;
  2. importjava.util.HashMap;
  3. importjava.util.Map;
  4. importorg.springframework.boot.SpringApplication;
  5. importorg.springframework.boot.autoconfigure.SpringBootApplication;
  6. importorg.springframework.web.bind.annotation.RequestMapping;
  7. importorg.springframework.web.bind.annotation.RestController;
  8. importcom.zyd.property.config.PropertiesListenerConfig;
  9. importcom.zyd.property.listener.PropertiesListener;
  10. @SpringBootApplication@RestControllerpublicclassApplaction{
  11. /****第四種方式:通過註冊監聽器(`Listeners`)+`PropertiesLoaderUtils`的方式**@authorzyd*@throwsUnsupportedEncodingException*@sinceJDK1.7*/
  12. @RequestMapping("/listener")publicMap<String,Object>listener(){
  13. Map<String,Object>map=newHashMap<String,Object>();
  14. map.putAll(PropertiesListenerConfig.getAllProperty());
  15. returnmap;
  16. }
  17. publicstaticvoidmain(String[]args)throwsException{
  18. SpringApplicationapplication=newSpringApplication(Applaction.class);
  19. //第四種方式:註冊監聽器application.addListeners(newPropertiesListener("app-config.properties"));application.run(args);}}

訪問結果:

[java]view plaincopy
      1. {"com.battle.name":"zyd",
      2. "com.battle.address":"Beijing",
      3. "com.battle.title":"使用Listeners+PropertiesLoaderUtils獲取配置檔案",
      4. "com.battle.type":"Springboot-Listeners",
      5. "com.battle.company":"in"}

https://blog.csdn.net/qq496013218/article/details/75146757#