如何覆盖Spring中@Value注入的字段值?
How to override a field value injected by @Value in Spring?
我有一个 class,其中使用 @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 来管理 class(因此注入其他依赖项)并且相同的 [= 需要其他测试28=] 使用不同的测试文件。
只需使用一个setter。无论如何,通常最好使用 setter 注入而不是字段注入。更好的是,完全转换为构造函数和 setter 注入,您通常可以用模拟替换 Spring 测试上下文。
你可以切换开发、生产、集成环境的配置文件
@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")
我有一个 class,其中使用 @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 来管理 class(因此注入其他依赖项)并且相同的 [= 需要其他测试28=] 使用不同的测试文件。
只需使用一个setter。无论如何,通常最好使用 setter 注入而不是字段注入。更好的是,完全转换为构造函数和 setter 注入,您通常可以用模拟替换 Spring 测试上下文。
你可以切换开发、生产、集成环境的配置文件
@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")