亲宝软件园·资讯

展开

Spring Boot配置文件加解密 Spring Boot 在启动时进行配置文件加解密的方法详解

云扬四海lv-1 人气:0
# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.context.config.ConfigFileApplicationListener,\

一、SmartApplicationListener介绍

/**
 * 指定支持哪些类型的事件
 */
boolean supportsEventType(Class<? extends ApplicationEvent> var1);

/**
 * 指定支持发生事件所在的类型
 */
boolean supportsSourceType(Class<?> var1);

如何在 SmartApplicationListener 实现监听解耦

1、我们只需在加载完成之后去加入一个监听器。
2、继承SmartApplicationListener接口
3、设置order属性决定监听器的顺序 ConfigFileApplicationListener.DEFAULT_ORDER + 1
4、将application.yml内容读取之后并修改

二、ConfigFileApplicationListener

三、最终结果:

public class AfterConfigListener implements SmartApplicationListener,Ordered {

 public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
 return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType) || ApplicationPreparedEvent.class.isAssignableFrom(eventType);
 }
 public void onApplicationEvent(ApplicationEvent event) {
 if (event instanceof ApplicationEnvironmentPreparedEvent) {
 }
 if (event instanceof ApplicationPreparedEvent) {
 }
 }
 @Override
 public int getOrder() {
 // 写在加载配置文件之后
 return ConfigFileApplicationListener.DEFAULT_ORDER + 1;
 }
}
public class AfterConfigListener implements SmartApplicationListener,Ordered {
 // 复制的ConfigFileApplicationListener文件内容
 public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
 return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType) || ApplicationPreparedEvent.class.isAssignableFrom(eventType);
 }

 public void onApplicationEvent(ApplicationEvent event) {
 // ApplicationEnvironmentPreparedEvent 是加载配置文件,初始化日志系统的事件。 
 if (event instanceof ApplicationEnvironmentPreparedEvent) {
 // 获得原来的password内容
 String password = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment().getProperty("spring.datasource.password");
 
 // 进行密码的解密
 System.setProperty("spring.datasource.password", SM4Utils.encryptData_ECB(password));
 }

 if (event instanceof ApplicationPreparedEvent) {
 }	
 }
 @Override
 public int getOrder() {
 // 设置该监听器 在加载配置文件之后执行
 return ConfigFileApplicationListener.DEFAULT_ORDER + 1;
 }

}
public class Application {

 public static void main(String[] args) {
 SpringApplication springApplication = new SpringApplication(Application.class);
 springApplication.addListeners(new AfterConfigListener());
 springApplication.run(args);
 }

}

总结

加载全部内容

相关教程
猜你喜欢
用户评论