【问题标题】:get actual spring profile inside WebApplicationInitializer在 WebApplicationInitializer 中获取实际的弹簧配置文件
【发布时间】:2016-04-01 18:45:47
【问题描述】:

我在 web.xml 中有以下条目:

<context-param>
     <param-name>spring.profiles.default</param-name>
     <param-value>test</param-value>
 </context-param>

和以下WebInitializer:

public class H2Starter implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        if (ArrayUtils.contains(rootContext.getEnvironment().getActiveProfiles(), "test")) {
            System.out.println("test profile is active");
        }
        container.addListener(new ContextLoaderListener(rootContext));
    }
}

当我使用测试配置文件 (mvn clean install jetty:run -Dspring.profiles.active=test) 启动应用程序时 - 执行进入 if 语句,我在控制台中看到结果。

如果我在没有明确配置文件的情况下启动应用程序 (mvn clean install jetty:run) - 执行不会进入 if 语句。从我这边看是错误的。 附言我尝试执行rootContext.getEnvironment().getDefaultProfiles(),但它返回值为default的单元素数组(根据我的意见应该是test

如何解决这个问题?

【问题讨论】:

  • 结帐this link了解更多信息。
  • 我不知道为什么你的getDefaultProfiles() 显示的是default 而不是test,但我认为你应该使用rootContext.getEnvironment().acceptsProfiles("test") 而不是ArrayUtils.contains(rootContext.getEnvironment().getActiveProfiles(), "test")

标签: java spring initialization spring-profiles


【解决方案1】:

您是否添加了:

  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

或者您可以尝试将其添加为 DispatcherServlet 的 init 参数,如下所示:

 <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>spring.profiles.active</param-name>
          <param-value>test</param-value>
      </init-param>
  </servlet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 2012-11-02
    • 2021-06-27
    • 1970-01-01
    • 2016-07-28
    • 2018-11-27
    • 2011-09-11
    • 2019-09-26
    相关资源
    最近更新 更多