• springboot读取配置文件的方法


    概述

    SpringBoot工程默认读取application.properties配置文件

    在Springboot中获取配置文件的方式

    方式二和方式三测试配置文件为springboot默认的application.properties文件

    application.properties文件:

    #			方式一
    
    com.hi.type3=Springboot - @ConfigurationProperties
    com.hi.title3=使用@ConfigurationProperties获取配置文件
    #map
    com.hi.login[username]=nameConfigurationProperties
    com.hi.login[password]=passwordConfigurationProperties
    com.hi.login[callback]=http://www.baidu.com
    #list
    com.hi.urls[0]=http://123.com
    com.hi.urls[1]=http://1234.com
    com.hi.urls[2]=http://12345.com
    com.hi.urls[3]=http://12346.com
    com.hi.urls[4]=http://12347.com
     
     
     #			方式二
     
    com.hi.type=Springboot - @Value
    com.hi.title=使用@Value获取配置文件
     
     
    # 		   方式三
    com.hi.type2=Springboot - Environment
    com.hi.title2=使用Environment获取配置文件
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    方式一(@ConfigurationProperties方式)

    配置类编写

    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Component//标识为Bean
    //prefix用来选择属性的前缀,也就是在remote.properties文件中的“com.hi”
    @ConfigurationProperties(prefix = "com.hi")
    //说明配置文件路径是config/remote.properties
    @PropertySource("classpath:config/remote.properties")
    //lombok注解,用于生成getter&setter方法
    @Data
    public class PropertiesConfig {
    
      public String type3;
      public String title3;
      public Map<String, String> login = new HashMap<String, String>();
      public List<String> urls = new ArrayList<>();
    } 
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    使用

    在想要使用配置文件的方法所在类上表上注解EnableConfigurationProperties(RemoteProperties.class)
    并使用@Autowired自动注入

    如下:

    @EnableConfigurationProperties(propertiesConfig.class)
    @RestController
    public class Test{
    	@Autowired
    	private PropertiesConfig propertiesConfig;
    	
    	@RequestMapping("/config")
    	public Map<String, Object> configurationProperties() {
    	  Map<String, Object> map = new HashMap<String, Object>();
    	  map.put("type", propertiesConfig.getType3());
    	  map.put("title", propertiesConfig.getTitle3());
    	  map.put("login", propertiesConfig.getLogin());
    	  map.put("urls", propertiesConfig.getUrls());
    	  return map;
    	}
    
    }
    
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    返回结果如下(我格式化过):

    {
      "title": "使用@ConfigurationProperties获取配置文件",
      "urls": [
        "http://123.com",
        "http://1234.com",
        "http://12345.com",
        "http://12346.com",
        "http://12347.com"
      ],
      "login": {
        "username": "nameConfigurationProperties",
        "callback": "http://www.baidu.com",
        "password": "passwordConfigurationProperties"
      },
      "type": "Springboot - @ConfigurationProperties"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    方式二(使用@Value注解方式)

    写一个controller

    @Value("${com.hi.type}")
    private String type;
    
    @Value("${com.hi.title}")
    private String title;
    
    @RequestMapping("/value")
    public Map<String, Object> value() throws UnsupportedEncodingException {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("type", type);
      // *.properties文件中的中文默认以ISO-8859-1方式编码,因此需要对中文内容进行重新编码
      map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));
      return map;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    返回结果如下(我格式化过):

    {
      "title": "使用@Value获取配置文件",
      "type": "Springboot - @Value"
    }
    
    • 1
    • 2
    • 3
    • 4

    方式三(使用Environment)

    @Autowired
    private Environment env;
    @RequestMapping("/env")
    public Map<String, Object> env() throws UnsupportedEncodingException {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("type", env.getProperty("com.hi.type2"));
      map.put("title", new String(env.getProperty("com.hi.title2").getBytes("ISO-8859-1"), "UTF-8"));
      return map;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    返回结果如下(我格式化过):

    {
      "title": "使用Environment获取配置文件",
      "type": "Springboot - Environment"
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    方式四(使用PropertiesLoaderUtils+Listeners)

    配置文件

    获取这个配置文件的内容:app-config.properties

    #### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式
    com.hi.type=Springboot - Listeners
    com.hi.title=使用Listeners + PropertiesLoaderUtils获取配置文件
    com.hi.name=namePropertiesLoaderUtils+Listeners
    com.hi.address=abc
    com.hi.company=in
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    PropertiesListener

    PropertiesListener.java:用来初始化加载配置文件
    即下面这个类

    import org.springframework.boot.context.event.ApplicationStartedEvent;
    import org.springframework.context.ApplicationListener;
    
    import com.hi.property.config.PropertiesListenerConfig;
    
    public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
    
      private String propertyFileName;
    
      public PropertiesListener(String propertyFileName) {
        this.propertyFileName = propertyFileName;
      }
    
      @Override
      public void onApplicationEvent(ApplicationStartedEvent event) {
        PropertiesListenerConfig.loadAllProperties(propertyFileName);
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    PropertiesListenerConfig

    PropertiesListenerConfig.java 加载配置文件内容

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Properties;
    
    import org.springframework.beans.BeansException;
    import org.springframework.core.io.support.PropertiesLoaderUtils;
    
    public class PropertiesListenerConfig {
      public static Map<String, String> propertiesMap = new HashMap<>();
    
      private static void processProperties(Properties props) throws BeansException {
        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
          String keyStr = key.toString();
          try {
            // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
            propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          } catch (java.lang.Exception e) {
            e.printStackTrace();
          }
        }
      }
    
      public static void loadAllProperties(String propertyFileName) {
        try {
          Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
          processProperties(properties);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    
      public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
      }
    
      public static Map<String, String> getAllProperty() {
        return propertiesMap;
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    执行

    使用controller去访问,获取内容

    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.hi.property.config.PropertiesListenerConfig;
    import com.hi.property.listener.PropertiesListener;
    
    @SpringBootApplication
    @RestController
    public class Applaction {
    
      @RequestMapping("/listener")
      public Map<String, Object> listener() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.putAll(PropertiesListenerConfig.getAllProperty());
        return map;
      }
    
      public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Applaction.class);
        // 第四种方式:注册监听器
        application.addListeners(new PropertiesListener("app-config.properties"));
        application.run(args);
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    返回结果如下(我格式化过):

    {
      "com.zyd.name": "namePropertiesLoaderUtils+Listeners",
      "com.zyd.address": "abc",
      "com.zyd.title": "使用Listeners + PropertiesLoaderUtils获取配置文件",
      "com.zyd.type": "Springboot - Listeners",
      "com.zyd.company": "in"
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    AI - 内容推荐算法
    Vue组合式 api 的常用知识点
    zookeeper教程
    MySQL事务管理 MVCC,隔离性详解
    Intel E810 DDP在VPP offload加速框架中的应用
    LLVM 插桩 LLVM IR PHI指令
    基于51单片机数字温度报警器_DS18B20可调上下限
    Tomcat一些漏洞的汇总
    有哪些SQL优化的手段?
    Ubuntu18/20运行ORB-SLAM3
  • 原文地址:https://blog.csdn.net/yyuggjggg/article/details/126018739