[英]How to override a field value injected by @Value in Spring?
我有一個類,使用@Value
從屬性注入一個字段:
public class MyClass {
@Value(${property.key})
private String filePath;
...
我的集成測試需要將filePath
更改為指向某些不同的文件。
在調用方法之前,我嘗試使用反射來設置它:
public class MyClassIT {
@Autowired MyClass myClass;
@Test
public void testMyClassWithTestFile1 {
ReflectionTestUtils.setField(myClass, "filePath", "/tests/testfile1.csv");
myClass.invokeMethod1();
...
但是當調用第一個方法時, @Value
注入將啟動並更改剛剛設置的值。 任何人都可以建議如何解決這個或另一種方法?
注意:我需要Spring來管理類(因此注入了其他依賴項),並且使用不同的測試文件需要對同一個類進行其他測試。
只需使用一個二傳手。 無論如何,通常最好使用setter注入而不是現場注入。 更好的是,完全轉換為構造函數和setter注入,通常可以用模擬替換Spring測試上下文。
嘗試彈簧剖析
您可以切換dev,prod,集成環境的配置文件
@Configuration
public class AppConfiguration {
@Value("${prop.name}")
private String prop;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
@Configuration
@Profile("dev")
@PropertySource("classpath:dev.properties")
public static class DevAppConfig {
}
@Configuration
@Profile("test")
@PropertySource("classpath:test.properties")
public static class TestAppConfig {
}
}
比在測試中使用@ActiveProfile("test")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.