簡體   English   中英

springboot測試使用ConfigurationProperties填寫Map

[英]Springboot test using ConfigurationProperties to fill Map

我有一個通用的 class 用於從我的應用程序 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

這是我用來根據一些鍵加載值的 class:

@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() 方法時,我得到了帶有鍵值的 map,但在我的測試中,我仍然無法注入 bean KeyStoreConfig

@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 而不是帶有鍵值的 map 我是否錯過了我的配置中的某些東西? 在此先感謝您的幫助

因此,由於您在@SpringBootTest上使用@ContextConfiguration批注,因此似乎禁用了某些 Spring 引導功能,例如加載application.propertiesapplication.yaml中指定的外部屬性。

要手動啟用它,您應該添加到您的測試 class: @EnableConfigurationProperties(KeyStoreConfig.class)

關於 spring 啟動測試的一些有用鏈接:

Spring 引導測試@ConfigurationProperties

Spring 引導中的@SpringBootTest 與@ContextConfiguration 與@Import

我還發現這篇文章很有趣,它是關於@ContextConfiguration@SpringApplicationConfiguration之間的區別,從 1.4 spring 引導版本開始不推薦使用@SpringBootTest

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM