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 的知道怎麼回事 這裏不多解釋

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章