SpringBoot SpringApplicationBuilder

时间:2015-03-09 06:30:38

标签: java spring cucumber spring-boot

我需要通过创建Cucumber集成测试来测试我的Spring应用程序代码。我正在使用SpringApplicationBuilder在触发实际逻辑之前启动我的应用程序并使用以下语法来执行此操作: -

application = new SpringApplicationBuilder()
    .parent(new Object[]{"classpath:file1.xml", "classpath:file2.xml"})
    .profiles("abc")
    .properties("name:value") [It has 5/6 (name:value) pairs here]*
    .showBanner(false)
    .logStartupInfo(true)
    .headless(true)
    .application()
    .run();

我的Spring应用程序正确启动。但是,它没有获取我传递给SpringApplicationBuilder()的属性(名称,值)对的值。我尝试了以下设置: -

  1. 使用上述名称值对
  2. 使用(名称,值)对的HashMap列出项目
  3. 创建ConfigurableEnvironment,检索MutablePropertySources 并在其中设置我的属性。
  4. 这些选项都不起作用,因此当应用程序启动并且代码尝试访问某些系统属性值时,它会中断。

    任何想法如何解决这个问题..非常感谢所有的帮助! 我需要这些属性是Spring属性,以确保应用程序正常工作。也许我可以用其他方式使用Spring道具测试我的代码?如果是这样,我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以按如下方式配置属性:

application = new SpringApplicationBuilder()
    .parent(new Object[]{"classpath:file1.xml", "classpath:file2.xml"})
    .profiles("abc")
    .properties("key1:test1", "key2:test2") 
    .showBanner(false)
    .logStartupInfo(true)
    .headless(true)
    .application()
    .run();

现在,使用@Value注释检索属性:

@Value("${key1}")
String val;

val变量将被赋值test1

答案 1 :(得分:0)

我自己也处理过同样的问题。 我的问题是我试图设置的值的键也在 application.properties 文件中设置。

从文件中删除条目后,它有效。