1 创建一个类实现EnvironmentPostProcessor
2 resources/META-INFO/spring.factories文件,配置实现类的全路径
以下是代码
实现类
java
package com.haier.configure.config;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import java.util.HashMap;
import java.util.Map;
/**
* @author A200
* @date 2024/12/18 16:58
*/
public class MyEnvPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
System.out.println("开始打印....");
Map<String, Object> bootstrapSource = new HashMap<>();
Map<String, Object> applicationSource = new HashMap<>();
MutablePropertySources propertySources = environment.getPropertySources();
for (PropertySource<?> propertySource : propertySources) {
String propertySourceName = propertySource.getName();
System.out.println("名称:"+propertySourceName);
if (StringUtils.containsIgnoreCase(propertySourceName, "bootstrap.yml")) {
System.out.println("bootstrap配置文件打印:");
Map<String,Object> map = (Map<String,Object>)propertySource.getSource();
bootstrapSource.putAll(map);
bootstrapSource.put("wei.age","18");
propertySources.remove(propertySourceName);
propertySources.addLast(new OriginTrackedMapPropertySource(propertySourceName, bootstrapSource));
continue;
}
if (StringUtils.containsIgnoreCase(propertySourceName, "application.yml")) {
System.out.println("application配置文件打印:");
Map<String,Object> map = (Map<String,Object>)propertySource.getSource();
applicationSource.putAll(map);
applicationSource.put("wei.name","longlonglong");
applicationSource.put("wei.flag","true");
propertySources.remove(propertySourceName);
propertySources.addLast(new OriginTrackedMapPropertySource(propertySourceName, applicationSource));
}
}
}
}
spring.factories文件
java
org.springframework.boot.env.EnvironmentPostProcessor=\
com.haier.configure.config.BootstrapDecryptEnvironmentPostProcessor,\
com.haier.configure.config.SystemDecryptEnvironmentPostProcessor,\
com.haier.configure.config.MyEnvPostProcessor
测试controller
java
@Value("${wei.age}")
private Integer weiage;
@Value("${wei.name}")
private String weiname;
@Value("${wei.flag}")
private Boolean weiflag;
@PostConstruct
public void init(){
System.out.println("打印配置哦:"+weiage);
System.out.println("打印配置哦:"+weiname);
System.out.println("打印配置哦:"+weiflag);
}