1. 程式人生 > >Spring boot中使用工具類 無需注入獲取.yml中的值

Spring boot中使用工具類 無需注入獲取.yml中的值

專案中經常需要將路徑URL等資訊單獨提出寫到配置檔案中,之前使用Spring時一般都是用 .properties檔案來存這些公共資訊,那麼如何在spring boot中優雅的使用.yml檔案存取呢、、

首先定義存放公共資訊的 .yml 配置檔案定義為 application-config.yml 檔案如下:

prairieManage:
   mapProps:
    key1: value1
    key2: value2
然後在住配置檔案引用新定義的檔案:如下:
server:
  port: 8080
  tomcat:
    uri-encoding: UTF-8
spring:
  profiles:
active: local,config
這裡注意:active這個屬性支援引入多個配置檔案 以逗號分隔.具體請檢視原始碼 active是以list接收的:

再頂一個物件 用於對映該配置檔案的值 如下:

@Component
@ConfigurationProperties(prefix = "prairieManage")
@Data
@Getter
@Setter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
public class YmlConfig {
    private Map<String,String> mapProps 
= new HashMap<>(); }
注意 該類中 變數要與配置檔案的一致 如配置檔案我們定義了一個以鍵值型別的 mapProns 那麼實體物件中屬性名也需要是該名.該物件中一定要有@Component

以及 Getter Setter 由於我們使用的 Lombok 所以這裡以註解代替 Getter Setter。

最後我們定義一個 Util 用於獲取該map中的值:

public class YmlConfigUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext 
= null; private static Map<String,String> propertiesMap =null; public YmlConfigUtil() { } public static String getConfigByKey(String key) throws JsonProcessingException { if (propertiesMap ==null){ YmlConfig ymlConfig = applicationContext.getBean(YmlConfig.class); propertiesMap = ymlConfig.getMapProps(); } return propertiesMap.get(key); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(YmlConfigUtil.applicationContext == null){ YmlConfigUtil.applicationContext = applicationContext; } } }
這裡注意 該util需要在啟動類注入進來:
@Import({YmlConfigUtil.class})
相信用Spring 的知道怎麼回事 這裡不多解釋