【发布时间】:2018-06-01 08:46:10
【问题描述】:
我正在设置 Spring Boot 应用程序,我希望使用自定义文件名而不是 application.yml 进行配置。原因是运行这些应用程序的服务器端 tomcat。
我定义了应用程序类:
@SpringBootApplication(scanBasePackages={"com.example"})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
System.setProperty("spring.config.name", "myapp");
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.properties("spring.config.name: myapp").sources(Application.class);
}
...
和名为 myapp.yml 的配置
在 JUnit 测试中我有以下注释:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
@ContextConfiguration(initializers = {ConfigFileApplicationContextInitializer.class})
@AutoConfigureMockMvc
public class UserTest {
...
以及 junit 的 pom 依赖项:
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.31</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<!-- if I remove this dependency then normal application works with custom name but if I have it in dependencies then mvn spring-boot:run does not find configuration either -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
我尝试了许多不同的方法,但无法按我的意愿工作。我想要我自己的配置文件名,然后使用 @ActiveProfiles 注释解决不同的配置。谢谢!
【问题讨论】:
-
你的
main方法在开始测试时没有执行,所以显然在那里设置东西是行不通的。使用@BeforeClass注释的方法来设置所需的属性。 -
我没有检查 main 是否真的发布了!如果我检查一下,我会自己找出其余的。感谢您提供有用的信息!
标签: java spring spring-boot junit