我们一般都写在yml或者properties文件中。
有没有一种办法,在配置文件中写密文,程序启动后自动解密,再使用这个解密后的密码进行连数据库或者redis?
jasypt就实现了这个功能。
https://github.com/ulisesbocchio/jasypt-spring-boot
这是jasypt的地址,上面有详细的使用说明和例子。目前版本已经更新到3.0.2
参照说明,我们看怎么使用。
目录
1,引入依赖
<!-- jasypt方式一 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<!-- jasypt方式二 -->
<!-- <dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>3.0.2</version>
</dependency> -->
2种方式引入依赖包。
第一种是你的springboot应用使用了@SpringBootApplication or @EnableAutoConfiguration注解就可以这样引入。
如果没有使用上面的注解,就用第二种方式。并且还需要在你的启动类上加注解:
@Configuration
@EnableEncryptableProperties
package com.example.gate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
//使用jasypt的第二种方式.如果你没用到@SpringBootApplication 或 @EnableAutoConfiguration就必须用下面2个注解,才能正常使用jasypt
//@Configuration
//@EnableEncryptableProperties
//@EnableCircuitBreaker
@ComponentScan(basePackages = "com.example")
@EnableDiscoveryClient
@SpringBootApplication
public class GateApplication {
public static void main(String[] args) {
SpringApplication.run(GateApplication.class, args);
}
}
其实还有更高级的用法,可以指定哪几个配置文件用jasypt。
//使用jasypt的第二种方式.如果你没用到@SpringBootApplication 或 @EnableAutoConfiguration就必须用下面2个注解,才能正常使用jasypt
//@Configuration
//@EnableEncryptableProperties
//具体指定配置文件的用法,其他配置文件不受jasypt影响
//@Configuration
//@EncryptablePropertySources({@EncryptablePropertySource("classpath:encrypted.properties"),
// @EncryptablePropertySource("classpath:encrypted2.properties")})
//@EnableCircuitBreaker
@ComponentScan(basePackages = "