0

我在 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 语句。从我这边看是错误的。PS我试图执行rootContext.getEnvironment().getDefaultProfiles()但它返回带有值的单元素数组default(应该test根据我的意见)

如何解决这个问题?

4

1 回答 1

0

你添加了:

  <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>
于 2015-12-27T21:27:03.220 回答