[英]Spring Boot context created programmatically does not set typesafe configuration properties
目前,我們正在將龐大的應用程序移至Spring Boot,這對於我們的生產代碼非常有效。 不幸的是,我們還必須適應所有測試。 我們現在想要在這里盡可能少地進行更改,並嘗試僅重寫幾乎每個測試用於創建公共類實例的一個大工廠類。 由於對象是通過方法調用創建的,因此我們不得不以編程方式創建上下文。 我們已經對其進行了管理,以將屬性插入到使用@Value進行注釋的字段中,但是不適用於Spring Boot引入的新方式( typesafe配置屬性 )。
這是一個說明問題的小例子:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
PropertySourcesPlaceholderConfigurer propertiesPostProcessor = new PropertySourcesPlaceholderConfigurer();
ropertiesPostProcessor.setLocation(new ClassPathResource("config/test.properties"));
context.addBeanFactoryPostProcessor(propertiesPostProcessor);
context.register(PropertyTest.class);
context.refresh();
PropertyTest bean = context.getBean(PropertyTest.class);
System.out.println("value="+bean.getValue());
System.out.println("valueTypesafe="+bean.getValueTypesafe());
PropertyTest類:
@Configuration
@ConfigurationProperties(prefix = "test")
@EnableConfigurationProperties
public class PropertyTest {
@Value("${test.value}")
private String value;
private String valueTypesafe;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getValueTypesafe() {
return valueTypesafe;
}
public void setValueTypesafe(String valueTypesafe) {
this.valueTypesafe = valueTypesafe;
}
}
test.properties
test.value="works"
test.valueTypesafe="works"
valueTypesafe="works"
輸出:
value="works"
valueTypesafe=null
我們還嘗試了這種方法的多種變體(其他注釋,上下文等),但沒有任何效果。 我試圖找出Spring Boot是如何做到的,但最終出現在EnableConfigurationPropertiesImportSelector和ConfigurationPropertiesBindingPostProcessor中 ,我們沒有對其進行管理以將它們集成到上下文中。
我們終於通過觸摸每個測試並添加@SpringApplicationConfiguration
來@SpringApplicationConfiguration
。 因此,不是手動創建上下文。 以編程的方式行不通,並且還會有其他缺點。
簡短的答案是您沒有使用Spring Boot。 如果要使用這些功能,則需要讓Spring Boot為您創建應用程序的上下文。 檢查SpringApplication
和SpringApplicationBuilder
。 在測試場景中,檢查SpringApplicationConfiguration
。
@ConfigurationProperties
注釋的POJO是針對Environment
處理的,上面的代碼未正確初始化它。 您可能想看看EnvironmentTestUtils
及其在Spring Boot測試套件中的用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.