【问题标题】:Use system-property as the value of @WebAppConfiguration使用 system-property 作为 @WebAppConfiguration 的值
【发布时间】:2017-08-03 09:26:11
【问题描述】:

是否可以使用系统属性作为@WebappConfiguration 注释的值?我尝试过类似的方法:

@WebAppConfiguration("#{systemProperties['webapproot'] ?: 'war'}")

但它似乎根本不起作用。春天有没有其他方法可以做到这一点?我不想通过我们的构建工具执行此操作,因为它会破坏从我们的 IDE 执行我们的集成测试。

【问题讨论】:

  • 使用 $ 而不是 # 也不起作用

标签: java spring-mvc spring-test spring-test-mvc


【解决方案1】:

@WebAppConfiguration 似乎既不支持 SpEL 也不支持占位符解析。

我通过以下方式对其进行了检查:我尝试使用@Value 注入系统属性并解析占位符。当我尝试注入一个不存在的属性@Value 时,分别抛出SpelEvaluationException: EL1008E: Property or field 'asd' cannot be found on object of type 'java.util.Properties'IllegalArgumentException: Could not resolve placeholder 'nonexistent_property' in value "${nonexistent_property}" 失败,而@WebAppConfigurationvalue 只是简单地将#{systemProperties.asd}${nonexistent_property} 初始化为简单的String

【讨论】:

    【解决方案2】:

    不,很遗憾不支持。

    提供给@WebAppConfigurationvalue 必须是显式资源路径,如类级JavaDoc 中所述。

    如果您希望我们考虑对value 属性进行动态评估,请随时打开JIRA issue 请求此类支持。

    问候,

    Sam(Spring TestContext 框架的作者

    【讨论】:

      【解决方案3】:

      我已经找到了解决这个问题的方法。我通过扩展 WebTestContextBootstrapper 编写了自己的 ContextBootsTraper,Spring 使用它来加载 WebAppConfiguration-Annotation 值。

      我扩展了功能,包括检查某个系统属性是否存在,如果存在则覆盖注释值:

       public class SystemPropTestContextBootstrapper extends WebTestContextBootstrapper {
      
          @Override
          protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
              WebAppConfiguration webAppConfiguration = AnnotationUtils.findAnnotation(mergedConfig.getTestClass(),
                      WebAppConfiguration.class);
              if (webAppConfiguration != null) {
                  //implementation ommited
                  String webappDir = loadWebappDirFromSystemProperty();
                  if(webappDir == null) {
                      webappDir = webAppConfiguration.value();
                  }
                  return new WebMergedContextConfiguration(mergedConfig, webappDir);
              }
      
              return mergedConfig;
          }
      }
      

      这个类然后可以与@BootstrapWith-Annotation 一起使用:

      @RunWith(SpringJUnit4ClassRunner.class)
      @BootstrapWith(SystemPropTestContextBootstrapper.class)
      @WebAppConfiguration("standardDir")
      public class SomeTest {
      
      }
      

      此解决方案使我能够从我的构建工具运行测试,同时保持从我的 IDE 运行测试的能力,这很棒。

      【讨论】:

        猜你喜欢
        • 2018-09-21
        • 1970-01-01
        • 2016-07-16
        • 2023-03-16
        • 2013-04-14
        • 2016-04-08
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        相关资源
        最近更新 更多