• 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

    import lombok.*;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Component
    @ConfigurationProperties(prefix = "prairieManage")
    @Data
    @Getter
    @Setter
    @EqualsAndHashCode
    @ToString
    @NoArgsConstructor
    public class YmlConfig {
        private Map<String,String> mapProps = new HashMap<>();
    }
    import com.fasterxml.jackson.core.JsonProcessingException;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    import java.util.Map;
    
    @Slf4j
    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) {
            if (propertiesMap ==null){
                YmlConfig ymlConfig = applicationContext.getBean(YmlConfig.class);
                propertiesMap = ymlConfig.getDatasource();
            }
            return propertiesMap.get(key);
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if(YmlConfigUtil.applicationContext == null){
                YmlConfigUtil.applicationContext  = applicationContext;
            }
        }
    }

    运用 比如我想获取url的值

    配置要注意

     log.info("[username]" + YmlConfigUtil.getConfigByKey("username"));

    非常的感谢

    https://blog.csdn.net/xiao______xin/article/details/73274830

    -------- 官方提供 的env 

    import org.springframework.core.env.Environment;

  • 相关阅读:
    最近工作
    有点感受
    日子有点快
    IDEA配置spring
    IDEA配置hibernate
    mysql插入中文乱码
    深夜配置一把struts2
    IDEA 配置SSH2
    找工作的事情
    YTU 2509: 奇怪的分式
  • 原文地址:https://www.cnblogs.com/lyon91/p/10395391.html
Copyright © 2020-2023  润新知