1 创建一个类实现EnvironmentPostProcessor
2 resources/META-INFO/spring.factories文件,配置实现类的全路径
以下是代码
实现类
- 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文件
- org.springframework.boot.env.EnvironmentPostProcessor=\
- com.haier.configure.config.BootstrapDecryptEnvironmentPostProcessor,\
- com.haier.configure.config.SystemDecryptEnvironmentPostProcessor,\
- com.haier.configure.config.MyEnvPostProcessor
复制代码
测试controller
- @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);
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |