如何在app.properties外部的属性中使用带有Jasypt的SpringBoot @ConfigurationProperties

时间:2016-11-28 20:45:29

标签: java spring spring-boot jasypt

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

这是我的主要课程:

@SpringBootApplication
@EnableEncryptableProperties
public class ServiceBaseApplication {

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

在测试评论中指出的stephane-nicoll之后,似乎Jasypt只选择位于application.properties的属性,那么我怎样才能将jasypt用于此文件外的属性?

2 个答案:

答案 0 :(得分:2)

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

干杯

答案 1 :(得分:0)

更好地直接注入EncryptablePropertyResolver并在@Value的设置器中解析加密的密钥:

@Autowired
private EncryptablePropertyResolver resolver;

private String yourExternalProperty;

@Value("${your.external.property}")
public void setYourExternalProperty(String value) {
        this.yourExternalProperty = resolver.resolvePropertyValue(value);
}

尽管我很高兴有人提出一个更通用的解决方案...

相关问题