springboot增加监听器和增加初始化的方式

文章介绍了在SpringBoot项目中如何自定义加密方式,对配置文件中的敏感信息如密码进行加密,并在应用启动时通过监听器或初始化器进行解密,确保安全加载到环境中。示例代码展示了如何使用`CustomDecryptListener`和`CustomDecryptInitializer`来处理加密的配置项。

工作需要自定义一个加密方式,然后在启动时进行解密,不用jasypt,查询得知可以用这两种方式实现,记录一下!

参考:

springboot配置文件密文解密

监听器:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
//        application.addInitializers(new CustomDecryptInitializer());
        application.addListeners(new CustomDecryptListener());
        application.run(args);
    }
}

package com.leadhead.modules.Cloud.config;

import com.leadhead.modules.Cloud.utils.EncryptionUtil;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.*;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ***
 * @description 配置文件解密监听器
 * @date 2023/2/24
 */

public class CustomDecryptListener  implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    private static final String PREFIX_ENCRYPT = "AAA[";
    private static final String SUFFIX_ENCRYPT = "]";
    private static final String Decrypt = "password";

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment env = event.getEnvironment();
        MutablePropertySources propertySources = env.getPropertySources();
        List<PropertySource<?>> updateList = new ArrayList<>();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof OriginTrackedMapPropertySource) {
                Map<String,Object>  map = new HashMap<>();
                OriginTrackedMapPropertySource newPropertySource = new OriginTrackedMapPropertySource(propertySource.getName(),map);
                Map<String,Object> source = (Map<String, Object>) propertySource.getSource();
                source.forEach((key, value) -> {
                    String propertyValue = String.valueOf(value);
                    if (StringUtils.hasText(key) && propertyValue.startsWith(PREFIX_ENCRYPT) && propertyValue.endsWith(SUFFIX_ENCRYPT)) {
                        propertyValue = propertyValue.replace(PREFIX_ENCRYPT, "");
                        propertyValue = propertyValue.replace(SUFFIX_ENCRYPT, "");
                        // 对加密内容进行解密
                        propertyValue = EncryptionUtil.decrypt(propertyValue, System.getProperty(Decrypt));
                    }
                    map.put(key, propertyValue);
                });
                updateList.add(newPropertySource);
            }
        }
        updateList.forEach(newPropertySource -> {
            propertySources.replace(newPropertySource.getName(),newPropertySource);
        });
    }
}

初始化:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.addInitializers(new CustomDecryptInitializer());
//        application.addListeners(new CustomDecryptListener());
        application.run(args);
    }
}

package com.leadhead.modules.Cloud.config;

import com.leadhead.modules.Cloud.utils.EncryptionUtil;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomDecryptInitializer implements ApplicationContextInitializer{
    private static final String PREFIX_ENCRYPT = "AAA[";
    private static final String SUFFIX_ENCRYPT = "]";
    private static final String Decrypt = "password";

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment env = applicationContext.getEnvironment();
        MutablePropertySources propertySources = env.getPropertySources();
        List<PropertySource<?>> list = new ArrayList<>();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof OriginTrackedMapPropertySource) {
                Map<String,Object> map = new HashMap<>();
                OriginTrackedMapPropertySource newPropertySource = new OriginTrackedMapPropertySource(propertySource.getName(),map);
                Map<String,Object> source = (Map<String, Object>) propertySource.getSource();
                source.forEach((key, value) -> {
                    String propertyValue = String.valueOf(value);
                    if (StringUtils.hasText(key) && propertyValue.startsWith(PREFIX_ENCRYPT) && propertyValue.endsWith(SUFFIX_ENCRYPT)) {
                        propertyValue = propertyValue.replace(PREFIX_ENCRYPT, "");
                        propertyValue = propertyValue.replace(SUFFIX_ENCRYPT, "");
                        // 对加密内容进行解密
                        propertyValue = EncryptionUtil.decrypt(propertyValue, System.getProperty(Decrypt));
                    }
                    map.put(key, propertyValue);
                });
                list.add(newPropertySource);
            }
        }
        list.forEach(newPropertySource -> {
            propertySources.replace(newPropertySource.getName(),newPropertySource);
        });
    }
}

other:

public static class Decoder implements ApplicationContextInitializer {

        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            ConfigurableEnvironment env = applicationContext.getEnvironment();
            MutablePropertySources propertySources = env.getPropertySources();
            for (PropertySource<?> propertySource : propertySources) {
                if (propertySource instanceof EnumerablePropertySource) {
//                if (propertySource instanceof OriginTrackedMapPropertySource) {
                    EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource;
                    for (String propertyName : enumerablePropertySource.getPropertyNames()) {
                        String propertyValue = String.valueOf(enumerablePropertySource.getProperty(propertyName));
                        if (StringUtils.hasText(propertyValue) && propertyValue.startsWith(PREFIX_ENCRYPT) && propertyValue.endsWith(SUFFIX_ENCRYPT)) {
                            propertyValue = propertyValue.replace(PREFIX_ENCRYPT, "");
                            propertyValue = propertyValue.replace(SUFFIX_ENCRYPT, "");
                            // 对加密内容进行解密
                            propertyValue = EncryptionUtil.decrypt(propertyValue, System.getProperty(Decrypt));
                            System.setProperty(propertyName,propertyValue);
                        }
                    }
                }
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值