【发布时间】:2018-11-09 11:06:01
【问题描述】:
我在一个用@Configuration 装饰的类中定义了一个Bean:
@Configuration
public class MyBeanConfig {
@Bean
public String configPath() {
return "../production/environment/path";
}
}
我有一个用@TestConfiguration 装饰的类,它应该覆盖这个Bean:
@TestConfiguration
public class MyTestConfiguration {
@Bean
@Primary
public String configPath() {
return "/test/environment/path";
}
}
configPath bean 用于设置外部文件的路径,该文件包含在启动期间必须读取的注册码。它用于@Component 类中:
@Component
public class MyParsingComponent {
private String CONFIG_PATH;
@Autowired
public void setCONFIG_PATH(String configPath) {
this.CONFIG_PATH = configPath;
}
}
在尝试调试时,我在每个方法以及测试配置类的构造函数中设置了一个断点。 @TestConfiguration 的构造函数断点被命中,所以我知道我的测试配置类实例化了,但是该类的 configPath 方法永远不会被命中。相反,普通@Configuration 类的configPath 方法被命中,MyParsingComponent 中的@Autowired String 始终是../production/environment/path,而不是预期的/test/environment/path。
不知道为什么会这样。任何想法将不胜感激。
【问题讨论】:
-
你的测试类是否用
@Import(MyTestConfiguration.class)注解? -
@SamBrannen 它不存在。并且添加它不起作用。但是将其更改为
@ContextConfiguration(MyTestConfiguration.class)确实如此。不过,仍然不明白为什么在没有ContextConfiguration的情况下会忽略 @Primary 注释。 -
如 Spring Boot 参考手册中所述,任何配置在带有
@TestConfiguration注释的顶级类中的 bean 都不会通过组件扫描被拾取。所以这就是为什么你必须明确声明它。 -
如果用
@TestConfiguration注释的类是测试类中的静态嵌套类,它将被自动使用。 -
如果这回答了您的问题,我可以将其作为正式的答案。 ;-)
标签: java spring-boot spring-test