【发布时间】:2020-02-25 20:03:11
【问题描述】:
我尝试创建一个简单的自定义 Spring Boot 启动器,它读取 application.properties 中的属性:
@EnableConfigurationProperties({ CustomStarterProperties.class })
@Configuration
public class CustomStarterAutoConfiguration {
@Autowired
private CustomStarterProperties properties;
@Bean
public String customStarterMessage() {
return properties.getMessage();
}
}
及其 ConfigurationProperties :
@ConfigurationProperties(prefix = "custom.starter")
public class CustomStarterProperties {
private String message;
/* getter and setter */
...
}
还有对应的application.properties和META-INF/spring.factories来启用autoconfiguration。
我有另一个项目将这个启动器声明为依赖项,我在其中编写了一个测试来查看是否创建了 customStarterMessage Bean:
@RunWith(SpringRunner.class)
@EnableAutoConfiguration
public class TotoTest {
@Autowired
String customStarterMessage;
@Test
public void loadContext() {
assertThat(customStarterMessage).isNotNull();
}
}
此测试失败(即使项目中有适当的 application.properties 文件),因为 application.properties 似乎没有被读取。
它适用于 @SpringBootTest 注释而不是 @EnableAutoConfiguration 但我想了解为什么 EnableAutoConfiguration 不使用我的 application.properties 文件,而据我了解所有 Spring AutoConfiguration 都是基于属性的。
谢谢
【问题讨论】:
-
你使用不同的包名吗?如果您包含的依赖项具有不同的包,除了您在第二个项目中的包之外,您还需要为依赖项中的包添加
@ComponentScan。 -
谢谢@AndreiSfat!我已经尝试使用正确的包声明
@ComponentScan但它不起作用:(
标签: spring-boot properties spring-boot-starter