![](/img/trans.png)
[英]How does Springboot use a database instead of a application.properties
[英]How to use SpringBoot @ConfigurationProperties with Jasypt in properties located outside application.properties
我正在使用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=)
我的控制器非常簡單:
@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入門程序中提供的文檔,但仍然沒有運氣。
這是我的主要課程:
@SpringBootApplication
@EnableEncryptableProperties
public class ServiceBaseApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceBaseApplication.class, args);
}
}
在測試stephane-nicoll在他的評論中指出的內容之后,Jasypt似乎只選擇位於application.properties
屬性,那么如何將jasypt與位於該文件外部的屬性一起使用?
在將加密密碼存儲在數據庫中並在啟動時加載該數據時,我遇到了同樣的問題。 但是Jasypt不能解密它,除非它在屬性文件中。 我已經向Jasypt成員發布了相同的問題。 檢查此鏈接以獲取他們的回復
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);
}
}
干杯
更好的直接注入EncryptablePropertyResolver
並解決的二傳手加密密鑰@Value
:
@Autowired
private EncryptablePropertyResolver resolver;
private String yourExternalProperty;
@Value("${your.external.property}")
public void setYourExternalProperty(String value) {
this.yourExternalProperty = resolver.resolvePropertyValue(value);
}
雖然我很高興有人能提出更通用的解決方案...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.