- 实现EnvironmentPostProcessor
import cn.hutool.http.HttpUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import java.io.IOException;
public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
// 方法将被调用两次,加载配置文件之前,加载配置文件之后(加载文件之前就不调用)
if (environment.getActiveProfiles().length == 0) {
return;
}
// 获取配置
String yamlContent = HttpUtil.get("");
// 将YAML内容转换为字节数组,以便加载
byte[] yamlBytes = yamlContent.getBytes();
// 创建一个ByteArrayResource对象,用于加载YAML内容
Resource resource = new ByteArrayResource(yamlBytes);
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
PropertySource<?> propertySource = null;
try {
propertySource = loader.load("remoteConfig", resource).get(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
environment.getPropertySources().addFirst(propertySource);
}
}
- 添加配置
resources->META-INF->spring.factories
org.springframework.boot.env.EnvironmentPostProcessor=\
com.你的包.CustomEnvironmentPostProcessor
启动项目即可