1

2

3

4

5

6

7

8

9

10

11

 

@Autowired

private StringEncryptor encryptor;

@Test

public void getPass() {

String name = encryptor.encrypt("userName");

String password = encryptor.encrypt("password");

System.out.println(name + "----------------");

System.out.println(password + "----------------");

}

之后只需要使用密文就行。

由于我这里是对数据库用户名和密码加密,所以还得有一个解密的过程。

利用 Spring Bean 的一个增强接口即可实现:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

 

@Component

public class DataSourceProcess implements BeanPostProcessor {

@Autowired

private StringEncryptor encryptor;

@Override

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

return bean;

}

@Override

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

if (bean instanceof DataSourceProperties){

DataSourceProperties dataSourceProperties = (DataSourceProperties) bean;

dataSourceProperties.setUsername(encryptor.decrypt(dataSourceProperties.getUsername())) ;

dataSourceProperties.setPassword(encryptor.decrypt(dataSourceProperties.getPassword()));

return dataSourceProperties ;

}

return bean;

}

}

这样就可以在真正使用时还原为明文。

同时也可以在启动命令中配置刚才的密码:

 

1

 

java -Djasypt.encryptor.password=password -jar target/jasypt-spring-boot-demo-0.0.1-SNAPSHOT.jar

总结

这样两个小技巧就讲完了,大家有 SpringBoot 的更多使用技巧欢迎留言讨论。

上文的一些实例代码可以在这里找到:

https://github.com/crossoverJie/springboot-cloud