如何在位于外特性使用SpringBoot @ConfigurationProperties与Jasypt application.properties中

问题描述:

我使用Spring 1.4.2启动和使用@ConfigurationProperties我的属性加载到我的财产豆这样的:如何在位于外特性使用SpringBoot @ConfigurationProperties与Jasypt application.properties中

@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 starter中提供的文档,但仍然没有运气。

这是我的主类:

@SpringBootApplication 
@EnableEncryptableProperties 
public class ServiceBaseApplication { 

    public static void main(String[] args) { 
     SpringApplication.run(ServiceBaseApplication.class, args); 
    } 
} 

检测一下stephane-nicoll在他的评论中指出后,似乎Jasypt只选择位于application.properties属性,所以我怎么可能用jasypt与位于该文件之外的属性?

+0

自述,看来你使用的是第一种方式,但是你配置了'jasypt .encryptor.password',这实际上并不是答案,但实际上当我想设置本地但总是得到exceptin作为'jasypt.encryptor.password'是必需的,如果我设置了密码,会遇到'确保加密/解密密码匹配“异常。 –

+0

@LipingHuang是的,我做了,无论如何,如果密码错误,我应该收到一个加密错误 –

+0

不要使用'locations',这个属性现在不推荐使用。也许jasypt只解密从通常位置加载的属性。如果删除'locations'属性并将这些属性放在'application.properties'中,会发生什么? –

我遇到了同样的问题,即将我的加密密码存储在数据库中,并在启动时加载该数据。但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); 
    } 
} 

干杯