首页 > 解决方案 > 通过 main 的命令行参数传递活动配置文件

问题描述

我正在尝试从我的 junit 测试用例中调用 Spring boot 主应用程序,如下所示并将配置文件设置为参数。

MyApplication.main(new String[] {"-Dspring.profiles.active=local"});

我有从 yml 文件读取的 @Value 配置。

yml

spring:
  profiles: local

subdivisions: test

爪哇

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class);
  }
}

测试用例

@RunWith(SpringJUnit4ClassRunner.class)
public class MyApplicationTest {


  @Test
  public void testMainApplication() {

    MyApplication.main(new String[] {"-Dspring.profiles.active=local"});

  }
}

当我运行我的测试用例时,我收到了这个错误 Could not resolve placeholder 'subdivisions' in value "${subdivisions}"

我猜测未设置导致此错误的活动配置文件。

我尝试了以下选项来传递 Spring Boot 主应用程序的活动配置文件

MyApplication.main(new String[] {"spring.profiles.active=local"});

提前致谢。对此的任何帮助表示赞赏..

标签: javaspring-boot

解决方案


我遇到了同样的问题,发现这种语法对我有用:

    @Test
    void main() {
        MyApplication.main(new String[]{"--spring.profiles.active=dev"});
    }

推荐阅读