SpringBoot2.X 项目使用外置绝对路径的配置文件

spring-boot-absolute-config

前言

  该工程是为解决应用部署应用时指定配置文件存放位置的问题.

  SpringBoot项目默认加载以下位置的配置文件:

1
2
3
4
classpath:
file:./
classpath:config/
file:./config/:

  想要指定外部的配置文件, 一种方法就是通过启动脚本来控制:

1
2
在启动脚本中添加:
-Dspring.config.location=文件绝对路径

但有时候有些项目需要兼容之前的老项目,就会遇到使用外部绝对路径的来指定配置文件了,每次都在启动脚本中添加,显然不是很合适.因此诞生了该工程.

实现方式

通过实现 EnvironmentPostProcessor 接口, 自定义实现方法:

1
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application)

来实现加载自定义配置文件.

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.github.springboot.absolute.config;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
 
/**
 * <p> 自定义环境加载策略
 * <p>需要在classpath下application.yml或application.properties中指定文件位置</p>
 * <p>key=config.file.absolute.path</p>
 *
 * @author lijinghao
 * @version : MyEnvironmentPostProcessor.java, v 0.1 2018年09月13日 下午4:55:55 lijinghao Exp $
 */
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
 
    /**,
     * 指定加载外部文件类型: [.properties], [.yml], [.yaml]
     */
    private static final String SUFFIX_TYPE_YML                             = ".yml";
    private static final String SUFFIX_TYPE_YAML                            = ".yaml";
    private static final String SUFFIX_TYPE_PROPERTIES                      = ".properties";
 
    /**
     * 指定外部配置文件路径的KEY
     */
    private static final String CONFIG_FILE_ABSOLUTE_PATH                   = "config.file.absolute.path";
 
    private static final int DEFAULT_ORDER                                  = ConfigFileApplicationListener.DEFAULT_ORDER + 1;
 
    /**
     * Post-process the given {@code env}.
     *
     * @param environment the env to post-process
     * @param application the application to which the env belongs
     */
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
 
        try {
 
            // Get file absolute path
            String path = environment.getProperty(CONFIG_FILE_ABSOLUTE_PATH);
            if (StringUtils.isEmpty(path)) {
                System.out.println("WARNING: External file path to be loaded is not configured.[config.file.absolute.path]");
                return;
            }
 
            System.out.println("INFO: Loading external file: "" + path + """);
 
            // Loading external file
            Resource resource = new PathResource(path);
 
            PropertySourceLoader loader;
 
            if (resource.exists() && resource.isFile()) {
                String filename = resource.getFilename();
                String fileSuffix = filename.substring(filename.indexOf("."));
 
                if (SUFFIX_TYPE_PROPERTIES.equalsIgnoreCase(fileSuffix)) {
                    loader = new PropertiesPropertySourceLoader();
 
                } else if (SUFFIX_TYPE_YML.equalsIgnoreCase(fileSuffix)
                        || SUFFIX_TYPE_YAML.equalsIgnoreCase(fileSuffix)) {
                    loader = new YamlPropertySourceLoader();
 
                } else {
                    throw new RuntimeException("Unsupported file types: " + fileSuffix);
                }
            }else {
                throw new FileNotFoundException("Cannot find the file : "" + path +""");
            }
 
            List<PropertySource<?>> sources = loader.load("externalFiles", resource);
            for (PropertySource<?> source : sources) {
                environment.getPropertySources().addLast(source);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
 
    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }
 
}

  在classpath:META-INF 下创建:spring.factories

  添加如下内容:

1
org.springframework.boot.env.EnvironmentPostProcessor=com.github.springboot.absolute.config.MyEnvironmentPostProcessor

使用说明

  1. 引入pom文件

    1
    2
    3
    4
    5
    <dependency>
         <groupId>com.github.springboot</groupId>
        <artifactId>absolute-config</artifactId>
        <version>1.0.0-RELEASE</version>
     </dependency>
  2. 在classpath下的配置文件中增加参数

    1
    2
    如,在application.yml中添加
    config.file.absolute.path: /opt/app/config/**/**/application.yml
  3. 重启项目

    重启项目时,会自动加载指定位置的配置文件;

注意事项

  1. 支持配置文件的格式

    1
    2
    1) classpath下SpringBoot默认加载application.properties、application.yml或application.yaml;
    2) 外置配置文件可以是以.properties、.yml或.yaml结尾(注意配置内容的格式);
  2. 外部加载的配置文件,不能使用原始配置文件的key

    1
    2
    如: server.port: 8090
     此参数只在classpath下的配置文件中生效,在外部加载的配置文件中不生效.

    此类key主要是在 ConfigFileApplicationListener 中进行加载.

  3. 引入了配置文件,但没配置config.file.absolute.path

    此时不会报错,只会在启动时打印提醒的语句.

  4. 配置了错误的config.file.absolute.path

    此时在项目启动时会打印出错误的异常栈,但不影响程序的正常启动.

    但是,如果你的项目中依赖了外置配置文件中的内容,可能会报错.

  具体源代码详见:https://github.com/lthaoshao/spring-boot-absolute-config

原文地址:https://www.cnblogs.com/lthaoshao/p/9676045.html
原文地址:https://www.cnblogs.com/jpfss/p/11009402.html