SpringBoot多环境配置动态解析
时间: 2023-06-17 08:03:55 浏览: 76
在Spring Boot中,可以通过多种方式配置多个不同的环境,比如properties文件、yaml文件、系统环境变量等。在多环境配置中,一个常见的需求是根据不同的环境来加载不同的配置文件,Spring Boot提供了一种很方便的方式来实现这个需求,即使用Spring Boot的Profile功能。
通过使用Profile,我们可以在不同的环境中加载不同的配置文件。具体实现方式如下:
1. 在application.properties文件中配置profiles.active属性,如:`spring.profiles.active=dev`。
2. 在resources目录下创建不同的配置文件,如application-dev.properties、application-prod.properties等。
3. 在配置文件中定义对应的配置项,如数据库连接、缓存配置等。
在程序运行时,Spring Boot会根据配置的profiles.active属性来决定加载哪个配置文件中的配置项。比如,当profiles.active=dev时,Spring Boot会加载application-dev.properties文件中的配置项。
而在实际项目中,我们可能需要根据不同的环境来动态解析配置文件,并将其配置到Spring Boot的Environment中,这时候可以使用Spring Boot提供的PropertySource来实现。具体实现方式如下:
1. 创建一个PropertiesLoaderUtils类,用于加载properties文件。
```java
public class PropertiesLoaderUtils {
private static final String DEFAULT_PROPERTIES = "application.properties";
public static Properties loadProperties(String... locations) throws IOException {
Properties properties = new Properties();
for (String location : locations) {
try (InputStream in = getResourceAsStream(location)) {
if (in == null) {
continue;
}
properties.load(in);
}
}
return properties;
}
private static InputStream getResourceAsStream(String location) {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(location);
if (in == null) {
in = PropertiesLoaderUtils.class.getClassLoader().getResourceAsStream(location);
}
if (in == null) {
in = ClassLoader.getSystemClassLoader().getResourceAsStream(location);
}
return in;
}
public static Properties loadDefaultProperties() throws IOException {
return loadProperties(DEFAULT_PROPERTIES);
}
}
```
2. 在程序启动时,读取配置文件并解析成PropertySource,然后将其添加到Spring Boot的Environment中。
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) throws IOException {
SpringApplication app = new SpringApplication(Application.class);
Environment env = app.run(args).getEnvironment();
Properties properties = loadProperties(env.getActiveProfiles());
PropertySource<?> propertySource = new PropertiesPropertySource("customProperties", properties);
((ConfigurableEnvironment) env).getPropertySources().addFirst(propertySource);
}
private static Properties loadProperties(String[] activeProfiles) throws IOException {
String[] locations = new String[activeProfiles.length + 1];
System.arraycopy(activeProfiles, 0, locations, 0, activeProfiles.length);
locations[activeProfiles.length] = "application.properties"; // 默认配置文件
return PropertiesLoaderUtils.loadProperties(locations);
}
}
```
在上面的代码中,我们首先获取了Spring Boot的Environment对象,并根据当前的Active Profiles加载对应的配置文件。然后,将配置文件解析成PropertySource,并将其添加到Environment中,这样就可以在程序中通过Environment获取到配置项了。
需要注意的是,如果多个配置文件中存在同名的配置项,后加载的配置项会覆盖之前的配置项。因此,在编写配置文件时,应该避免定义同名的配置项,以免造成不必要的麻烦。