在Spring MVC中从环境变量设置活动配置文件

巴勃罗·乔默(Pablo Jomer)

我需要在我的构造后钩子中访问应用程序上下文。这有可能吗,如何以编程方式完成呢?

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();
}

请指教。

巴勃罗·乔默(Pablo Jomer)

我最终像这样创建了一个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>

这真的很好。谢谢您的帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在IntelliJ中设置spring活动配置文件环境变量

在Spring-boot中设置默认的活动配置文件

基于docker环境变量切换spring配置文件不起作用

如何在Spring中以编程方式获取当前的活动/默认环境配置文件?

在Spring Boot中从命令行设置活动配置文件和配置位置

在spring配置文件中设置资源

在Visual Code启动文件中编辑Spring Boot应用程序配置环境变量

如何在Vertx中设置类似于Spring Boot的活动配置文件

在app.props中定义的活动配置文件,但是环境变量返回活动配置文件的空数组

Docker环境变量中的Spring属性

通过环境变量设置Spring Boot Yaml配置列表属性

通过spring config + spring config中的环境变量设置logback属性

在python脚本中调用bash配置文件以设置环境变量

使用YAML而不是Properties和@Profile设置Spring 4.1配置文件环境

如何为Spring Boot应用程序的Gradle构建设置活动配置文件?

以编程方式创建Spring上下文时如何设置活动配置文件?

如何在构建 bootJar 时在 Spring Boot 上设置活动配置文件?

访问Jam配置文件中的环境变量

将Kubernetes yaml配置中定义的环境值传递给java spring配置文件

Spring 配置附加位置作为 docker-compose 中的环境变量

如何在映射到Spring配置类中的列表的环境变量中转义逗号

NLog环境变量配置文件

NodeJs环境变量与配置文件

如何在spring xml配置中注入环境变量?

Spring启动配置文件和环境中的日志文件名

根据Weblogic环境变量确定Spring Boot中的环境

通过环境变量在Spring Boot中设置日志记录级别

如何通过环境变量设置名称中带有下划线的Spring Boot属性?

如何在 application.yml 中设置环境变量 - Spring Boot