我正在使用 Spring Boot 1.4.2 并使用 @ConfigurationProperties
将属性加载到属性 bean,如下所示:
@ConfigurationProperties(prefix="my.prop", locations = "classpath:properties/myprop.properties")
@Configuration
public class MyProp {
private String firstName;
private String lastName;
// getters & setters
}
我还有这个属性文件:
my.prop.firstName=fede
my.prop.lastName=ENC(MzWi5OXKOja3DwA52Elf23xsBPr4FgMi5cEYTPkDets=)
我的 Controller 非常简单:
@RestController
public class MyController {
@Autowired
private MyProp prop;
@GetMapping("/")
public String get() {
System.out.println(String.format("UserConfig - user: %s, lastName: %s", prop.getFirstName(), prop.getLastName()));
return "something";
}
}
一切正常,我的属性已加载,我的输出是:
2016-11-28 14:36:30,402 INFO 9780 --- [qtp792210014-27] c.c.b.m.c.c.MyController : [OhxxugGR] UserConfig - user: fede, lastName: ENC(MzWi5OXKOja3DwA52Elf23xsBPr4FgMi5cEYTPkDets=)
我确认一切正常,我想使用 jasypt 来加密和使用我的属性,但是我将此依赖项添加到了 pom 中:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.9</version>
</dependency>
但是 jasypt 没有解密,正如您在日志中看到的那样。我已阅读此 jasypt starter 中提供的文档但还是没有运气。
这是我的主课:
@SpringBootApplication
@EnableEncryptableProperties
public class ServiceBaseApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceBaseApplication.class, args);
}
}
测试后stephane-nicoll在他的评论中指出,Jasypt 似乎只选择位于 application.properties
中的属性,那么我如何将 jasypt 与位于该文件外部的属性一起使用?
最佳答案
我遇到了同样的问题,我将加密密码存储在数据库中并在启动时加载该数据。但 Jasypt 无法解密它,除非它在属性文件中。我向 Jasypt 的 friend 们提出了同样的问题。检查此链接以获取他们的回复
https://github.com/ulisesbocchio/jasypt-spring-boot/issues/31#event-752104289
最后,这就是我最终所做的。
@Configuration
public class JasyptConfig {
@Value("${jasypt.encryptor.password}")
public String encryptDecryptKey; // This is the key I used to encrypt my password
@Bean
public TextEncryptor createTextDecryptor(){
BasicTextEncryptor textDecryptor = new BasicTextEncryptor();
textDecryptor.setPassword(encryptDecryptKey);
return textDecryptor;
}
}
在我必须解密的类里面,我这样做了
@Component
public class PasswordUtil {
private final TextEncryptor textDecryptor;
@Autowired
public PasswordUtil(final TextEncryptor textDecryptor) {
this.textDecryptor = textDecryptor;
}
public String decrypt(String encryptedText){ // This encryptedText is the one like *ENC(....)*
return textDecryptor.decrypt(encryptedText);
}
}
干杯
关于java - 如何在位于 application.properties 外部的属性中将 Spring Boot @ConfigurationProperties 与 Jasypt 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40853151/