SpringBoot 配置文件外置方案
方案一:项目启动时设置环境变量
在Application文件中的configure方法添加如下代码(注:会影响同一jvm环境中的其他项目):
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); yaml.setResources(new FileSystemResource(“yml文件地址”)); System.getProperties().putAll(Objects.requireNonNull(yaml.getObject()));
方案二:基于SpringCloud的PropertySourceLocator接口加载配置文件
在pom文件中添加依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> <version>2.2.1.RELEASE</version> </dependency>
实现PropertySourceLocator接口,完整代码如下:
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;
import java.util.*;
@Slf4j
@Order(0)
public class IvPropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
return new MapPropertySource("iv", ymlParse("/opt/weblogic/config/application-dev.yml"));
}
/**
* yml文件解析
*/
private Map<String, Object> ymlParse(String location) {
log.info("开始加载系统配置文件 >>>>> {}", location);
YamlMapFactoryBean yamlFactory = new YamlMapFactoryBean();
yamlFactory.setResources(new FileSystemResource(location));
Map<String, Object> result = new LinkedHashMap<>();
flattenedMap(result, Objects.requireNonNull(yamlFactory.getObject()), null);
return result;
}
protected void flattenedMap(Map<String, Object> result, Map<String, Object> dataMap,
String parentKey) {
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
String fullKey = StringUtils.isEmpty(parentKey) ? key : key.startsWith("[")
? parentKey.concat(key) : parentKey.concat(".").concat(key);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
flattenedMap(result, map, fullKey);
continue;
} else if (value instanceof Collection) {
int count = 0;
Collection<Object> collection = (Collection<Object>) value;
for (Object object : collection) {
flattenedMap(result,
Collections.singletonMap("[" + (count++) + "]", object),
fullKey);
}
continue;
}
result.put(fullKey, value);
}
}
}
