【发布时间】:2021-12-02 03:59:48
【问题描述】:
我正在尝试使用 Spring Boot 设置 Jasypt 工作流程。如this Tutorial 中所述,我添加了所需的依赖项:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
用:加密密码:
mvn jasypt:encrypt-value -Djasypt.encryptor.password=javatechie -Djasypt.plugin.value=Password
创建了一个encrypted.properties并将加密的密码放入其中:
secret.property=ENC(nrmZtkF7T0kjG/VodDvBw93Ct8EgjCAaskygdq8PHapYFnlX6WsTwZZOxWInq+i)
注释了我的主类:
@SpringBootApplication
@EnableEncryptableProperties
@PropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
在另一个类中我尝试加载解密后的值:
@Component
public class MyOtherClass {
private static final Logger LOGGER = LoggerFactory.getLogger(MyOtherClass.class);
@Value("${secret.property}")
String secret;
public MyOtherClass() {
LOGGER.info("PW: " + secret);
}
}
但我只是得到:
PW: null
当我将值更改为不存在的东西时:
@Value("${abc.def}")
String secret;
我得到了预期的错误:
java.lang.IllegalArgumentException:无法解析值“${abc.def}”中的占位符“abc.def”
所以好像找到了我的实际值secret.property,但是为什么是null呢?
【问题讨论】:
-
您能否确保您的
encrypted.properties文件已正确加载?我的意思是我看不到任何带有@PropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")的@Configuration。尝试放置一些虚拟键值并将其放入您的组件中。 -
检查日志是否有任何 Jasypt 异常。
-
@sushant:在日志中显示:
o.s.c.e.PropertySourcesPropertyResolver : Found key 'secret.property' in PropertySource 'environmentProperties' with value of type String。但值仍然是null。 -
@KumarAshutosh:
@PropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")在我的Main.class中。 -
您正在访问 bean 中的注入属性。 Spring首先实例化bean,然后注入值。您可以尝试访问构造函数之外的值,例如 bean 方法。
标签: java spring spring-boot encryption jasypt