在Bean实例化之前修改yml配置项,实现对nacos client连接时的密码进行动态解密,密码由jasypt加密

nacos client配置项

spring:
  application:
    name: @artifactId@
  cloud:
    nacos:
      username: nacos
      password: 加密的密码

扩展EnvironmentPostProcessor

public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		try {
			final String PROPERTY_NAME = "spring.cloud.nacos.password";
			// 读取YAML文件并获得Properties对象
			ClassLoader classLoader = AuroraEnvironmentPostProcessor.class.getClassLoader();
			InputStream inputStream = classLoader.getResourceAsStream("application.yml");
			HashMap<String, Object> hashMap = YamlUtil.load(inputStream, HashMap.class);
			// 指定配置项的值
			HashMap<String, Object> spring = (HashMap<String, Object>) hashMap.get("spring");
			HashMap<String, Object> cloud = (HashMap<String, Object>) spring.get("cloud");
			HashMap<String, Object> nacos = (HashMap<String, Object>) cloud.get("nacos");
			String nacosPassword = (String) nacos.get("password");
			// 修改指定配置项的值
			StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
			standardPBEStringEncryptor.setPassword("JASYPT_PASSWORD");
			standardPBEStringEncryptor.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
			standardPBEStringEncryptor.setIvGenerator(new RandomIvGenerator());
			Properties properties = new Properties();
			properties.put(PROPERTY_NAME, standardPBEStringEncryptor.decrypt(nacosPassword));
			// 覆写配置项的值
			MutablePropertySources propertySources = environment.getPropertySources();
			propertySources.addFirst(new PropertiesPropertySource("nacos-properties", properties));
		} catch (Exception e) {
			log.error("setProperties fail", e);
		}
	}

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}

通过SPI使自定义的配置生效
在 src/main/resources下新建META-INF/spring.factories文件,写入内容

org.springframework.boot.env.EnvironmentPostProcessor=com.test.config.MyEnvironmentPostProcessor
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值