修改YAML文件里面的属性值

import com.cnpc.a11wlw.common.util.encrypt.CommonConstant;
import com.cnpc.a11wlw.common.util.encrypt.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.util.Properties;

@Configuration
@Slf4j
public class TestYamlConfig {


/**
* 注册 PropertySourcesPlaceholderConfigurer,加载自定义 YAML 文件
*/

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws Exception {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();

// 指定 YAML 文件路径(类路径下的 bootstrap.yml)
Resource resource = new ClassPathResource("bootstrap.yaml");
//加载指定的配置文件
configurer.setLocations(resource);
// 2. 设置 YAML 解析工厂(关键:Spring 需通过 YamlPropertiesFactoryBean 解析 YAML)
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(resource);
//将 YAML 配置文件的内容解析为 Java 原生的 Properties 对象
Properties properties = yamlFactory.getObject();
String configPassword = properties.getProperty("spring.cloud.nacos.config.password");
String desConfigPassword = EncryptUtils.resolveContet(CommonConstant.SECRET_KEY, configPassword);
properties.setProperty("spring.cloud.nacos.config.password",desConfigPassword);
String discoveryPassword = properties.getProperty("spring.cloud.nacos.discovery.password");
String desDiscoveryPassword = EncryptUtils.resolveContet(CommonConstant.SECRET_KEY, discoveryPassword);
properties.setProperty("spring.cloud.nacos.discovery.password",desDiscoveryPassword);
//将已解析好的 Properties 键值对集合,直接注入到 PropertySourcesPlaceholderConfigurer 中,
// 作为 Spring 容器的 “配置源” 之一
configurer.setProperties(properties);

// 3. 允许占位符未找到时不报错(可选,根据需求配置)
//configurer.setIgnoreUnresolvablePlaceholders(true);

return configurer;
}

}

posted @ 2025-11-27 09:19  雪的回忆  阅读(5)  评论(0)    收藏  举报