【springboot】读取外部的设置文件

[复制链接]
发表于 2025-12-18 23:12:35 | 显示全部楼层 |阅读模式
一、利用场景

假设有一个生意业务商品的体系,客户盼望能机动修改首页保举商品的个数 num。
假如 num 是写在代码里的固定值,每次修改,开发职员就得重新将体系打包摆设上线,费时费力。
但假如 num 是写在 jar 包的外部设置文件中,开发职员只须要修改该外部设置文件,然后重启已经摆设上线的体系,就可以到达机动修改 num 的结果啦。
二、代码实现

(一)application.yml 的设置

设置外部文件的路径,这里是 customer.yml,和 src 文件夹同级,如图。
  1. customer:
  2.   path: customer.yml
复制代码

(二)编辑 customer.yml

这里设置了一个 num,值是 5
  1. num: 5
复制代码
(三)自界说方法读取外部设置文件

  1. package com.xxx.env;
  2. import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.env.EnvironmentPostProcessor;
  5. import org.springframework.core.env.ConfigurableEnvironment;
  6. import org.springframework.core.env.PropertiesPropertySource;
  7. import org.springframework.core.env.PropertySource;
  8. import org.springframework.core.io.FileSystemResource;
  9. import org.springframework.core.io.Resource;
  10. import java.io.File;
  11. import java.util.Properties;
  12. public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
  13.     @Override
  14.     public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
  15.         //自定义配置文件,对应 application.yml 里的前缀
  16.         String profiles = environment.getProperty("customer.path");
  17.         //加载成PropertySource对象,并添加到Environment环境中
  18.         File file = new File(profiles);
  19.         Resource resource = new FileSystemResource(file);
  20.         environment.getPropertySources().addLast(loadProfiles(resource));
  21.     }
  22.     /**
  23.      * 加载单个配置文件
  24.      * @param resource
  25.      * @return
  26.      */
  27.     private PropertySource<?> loadProfiles(Resource resource) {
  28.         // 判断资源是否存在
  29.         if (!resource.exists()) {
  30.             throw new IllegalArgumentException("资源" + resource + "不存在");
  31.         }
  32.         // 判断后缀名,兼容 .yml 文件和 .properties 文件
  33.         if (resource.getFilename().contains(".yml")) {
  34.             return loadYaml(resource);
  35.         } else {
  36.             return loadProperty(resource);
  37.         }
  38.     }
  39.     /**
  40.      * 加载properties格式的配置文件
  41.      *
  42.      * @param resource
  43.      * @return
  44.      */
  45.     private PropertySource loadProperty(Resource resource) {
  46.         try {
  47.             //从输入流中加载一个Properties对象
  48.             Properties properties = new Properties();
  49.             properties.load(resource.getInputStream());
  50.             return new PropertiesPropertySource(resource.getFilename(), properties);
  51.         } catch (Exception ex) {
  52.             throw new IllegalStateException("加载配置文件失败" + resource, ex);
  53.         }
  54.     }
  55.     /**
  56.      * 加载yml格式的配置文件
  57.      *
  58.      * @param resource
  59.      * @return
  60.      */
  61.     private PropertySource loadYaml(Resource resource) {
  62.         try {
  63.             YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
  64.             factory.setResources(resource);
  65.             //从输入流中加载一个Properties对象
  66.             Properties properties = factory.getObject();
  67.             return new PropertiesPropertySource(resource.getFilename(), properties);
  68.         } catch (Exception ex) {
  69.             throw new IllegalStateException("加载配置文件失败" + resource, ex);
  70.         }
  71.     }
  72. }
复制代码
(四)将自界说方法注册到 Spring Boot


在 src/main/resources/META-INF/spring.factories 中注册自界说方法 MyEnvironmentPostProcessor,如下
  1. # 将自定义方法的路径填进去
  2. org.springframework.boot.env.EnvironmentPostProcessor=com.xxx.env.MyEnvironmentPostProcessor
复制代码
(五)利用外部设置文件的设置

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.core.env.Environment;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. public class TestController {
  7.     @Autowired
  8.     private Environment environment;
  9.     @GetMapping("/test")
  10.     public void test() {
  11.         // 读取 num 配置值,不为空则输出
  12.         String num = environment.getProperty("num");
  13.         if (num != null && !num.equals("")) {
  14.             System.out.println("num = " + num);
  15.         } else {
  16.             System.out.println("num is null or ''");
  17.         }
  18.     }
  19. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表