我有一个带有@Configuration注释的Spring配置类的Spring Boot应用程序,其中包含一些带有@Value注释的字段。对于测试,我想用自定义测试值替换这些字段值。
@Configuration
@Value
不幸的是,这些测试值不能使用简单的属性文件,(字符串)常量或类似属性覆盖,而是 必须 使用一些自定义的书面属性来解析Java类(例如TargetProperties.getProperty("some.username"))。
TargetProperties.getProperty("some.username")
我的问题是,当我在测试配置中PropertySource向中添加自定义项时ConfigurableEnvironment,已经太迟了,因为PropertySource它将在创建eg 之后 添加RestTemplate。
PropertySource
ConfigurableEnvironment
RestTemplate
我如何可以覆盖@Value注释字段 内 一@Configuration类获得性 编程 通过自定义的Java代码 之前, 什么都被初始化?
@Configuration public class SomeConfiguration { @Value("${some.username}") private String someUsername; @Value("${some.password}") private String somePassword; @Bean public RestTemplate someRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add( new BasicAuthorizationInterceptor(someUsername, somePassword)); return restTemplate; } }
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class SomeTest { @SpringBootConfiguration @Import({MySpringBootApp.class, SomeConfiguration.class}) static class TestConfiguration { @Autowired private ConfigurableEnvironment configurableEnvironment; // This doesn't work: @Bean @Lazy(false) // I also tried a @PostConstruct method public TargetPropertiesPropertySource targetPropertiesPropertySource() { TargetPropertiesPropertySource customPropertySource = new TargetPropertiesPropertySource(); configurableEnvironment.getPropertySources().addFirst(customPropertySource); return customPropertySource; } } }
您可以在生产案例中使用构造函数注入,这使它可以手动设置配置:
@Configuration public class SomeConfiguration { private final String someUsername; private final String somePassword; @Autowired public SomeConfiguration(@Value("${some.username}") String someUsername, @Value("${some.password}") String somePassword) { this.someUsername = someUsername; this.somePassword = somePassword; } ... ) } @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class SomeTest { private SomeConfiguration config; @Before public init() { config = new SomeConfiguration("foo", "bar"); } }