java - Springboot测试使用ConfigurationProperties填充Map
问题描述
我有一个通用类,用于从我的应用程序 yaml 文件中加载一些键,这是我的 yaml 文件:
errabi.security:
keyStores:
jwt:
type: JKS
location: classpath:keystore.jks
keyStorePassword: password # to be encrypted
keyPassword: password # to be encrypted
keyAlias: errabi
jwe:
type: JKS
location: classpath:keystore.jks
keyStorePassword: password # to be encrypted
keyPassword: password # to be encrypted
keyAlias: errabi
这是我用来根据一些键加载值的类:
@Configuration
@ConfigurationProperties(prefix = "errabi.security")
public class KeyStoreConfig {
private Map<String, KeyStoreConfig.KeyStoreConfiguration> keyStores;
public Map<String, KeyStoreConfiguration> getKeyStores() {
return keyStores;
}
public void setKeyStores(Map<String, KeyStoreConfiguration> keyStores) {
this.keyStores = keyStores;
}
public static class KeyStoreConfiguration {
private String type;
private String location;
private char [] keyStorePassword;
private char [] keyPassword;
private String keyAlias;
// getters and setters
}
}
在我的应用程序中,当我调用 KeyStoreConfig.getKeyStores() 方法时,我得到了带有键值的映射,但在我的测试中,我仍然无法注入 beanKeyStoreConfig
@SpringBootTest
@ContextConfiguration(classes = KeyStoreConfig.class)
class JWEUtilTest extends Specification {
@Autowired
private KeyStoreConfig keyStoreConfig;
// in the debug mode the KeyStoreConfig.getKeyStores() return a null instead of a map with keyvalues
}
在我的测试过程中,NullPointerException
当我调试时,我看到KeyStoreConfig.getKeyStores()
返回 null 而不是带有键值的映射,我是否错过了配置中的某些内容?提前感谢您的帮助
解决方案
因此,由于您@ContextConfiguration
在.@SpringBootTest
application.properties
application.yaml
要手动启用它,您应该添加到您的测试类:@EnableConfigurationProperties(KeyStoreConfig.class)
.
有关 Spring Boot 测试的一些有用链接:
Spring Boot 测试@ConfigurationProperties
@SpringBootTest 与 @ContextConfiguration 与 Spring Boot 中的 @Import
我还发现这篇@ContextConfiguration
文章很有趣,它是关于和之间的区别@SpringApplicationConfiguration
,从 1.4 春季启动版本开始不推荐使用@SpringBootTest
.
推荐阅读
- javascript - 如何每 10 分钟调用一次更新的方法?
- stata - 用于事件研究的滞后和领先变量虚拟变量 - Stata
- python - Python:将python编译成EXE后出现问题
- java - GPS位置不会显示在手机上
- python - 掷骰子游戏:奇数得到一个小数,偶数得到一个红利
- python - Repeating entity in replacing entity with their entity label using spacy
- python - Troubles aligning ttk widget
- java - Spring Boot with embedded ActiveMQ Artemis JMS server
- plotly - Blank plotly plots in Google Colab
- go - 如何在命令行界面中存储会话