在spring mvc中从环境变量设置活动配置文件

时间:2015-08-13 11:26:41

标签: java spring

我需要在postconstruction钩子中访问应用程序上下文。这是可能的吗?如何以编程方式完成?

public final void systemSetup() throws Exception {
  // I would like to set active profile here so I need the context.
  context.getEnvironment().setActiveProfiles(APP_ENV.toLowerCase()); 
  PrintVariables();
  InitializeLimeService();
  InitializeSGCSClient();
}

请建议。

1 个答案:

答案 0 :(得分:0)

我最终创建了一个像这样的ApplicationContextInitializer。

package com.realitylabs.spa.tool;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author Pablo Karlsson
 *
 * ConfigurableApplicationContextInitializer sets the spring profile
 * before application initialization so we can use dependency injection
 * based on profile. This allows us to mock services like SGCSClientService
 * In development mode.
 */
public class ConfigurableApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

  @Override
  public void initialize(ConfigurableApplicationContext context) {

    String APP_ENV = System.getenv("APP_ENV");

    if(APP_ENV == null) {
      throw new RuntimeException("Please set APP_ENV to production or development");
    }

    APP_ENV = APP_ENV.toLowerCase();

    if(!APP_ENV.equals("development") && !APP_ENV.equals("production")) {

      throw new RuntimeException("Please set APP_ENV to production or development");
    }

    context.getEnvironment().setActiveProfiles(APP_ENV);
  }
}

我将以下行添加到我的web.xml

  <context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.realitylabs.spa.tool.ConfigurableApplicationContextInitializer</param-value>
  </context-param>

这非常有效。谢谢你的帮助!