Spring 以编程方式启动设置配置文件

Spring Boot Programmatically setting profiles

如何在 spring 引导应用程序中设置活动配置文件。此应用程序将独立部署 Tomcat。

我有 2 个 属性 文件 application-{profile}.properties。

我的申请class

    @SpringBootApplication
        public class Application extends SpringBootServletInitializer {

            @Override
            protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {        
                return application.sources(Application.class);
            }

            public static void main(String[] args) {
               System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
 ApplicationContext ctx = SpringApplication.run(Application.class, args);
      }
    }

如果我 运行 嵌入了 tomcat 的应用程序,则开发配置文件设置为活动状态并且运行良好。但是当我独立部署时 tomcat。没用。

我试图在配置方法中设置活动配置文件。但是当我从上下文中获取环境时,我得到了空指针异常。

有关如何设置活动配置文件的任何帮助。

您可以将配置文件作为 vm 参数放在 catalina.sh

中,而不是动态激活配置文件
CATALINA_OPTS="-Dspring.profiles.active=dev"

我也遇到了同样的问题,折腾了半天,结果是这样的:

    @SpringBootApplication
    public class MyApplication extends SpringBootServletInitializer {

        public static void main(String[] args) {
            System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
            SpringApplication.run(MyApplication.class, args);
        }

        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev"); 
            super.onStartup(servletContext);
        }
    }
System.setProperty("spring.profiles.active", "dev");

您可以在启动时设置其他配置文件:

   SpringApplication springApp = new SpringApplication(Main.class);
   springApp.setAdditionalProfiles("profile1", "profile2");
   springApp.run(args);

另一种在 Spring Boot 2 中实现的方法是使用 SpringApplicationBuilder:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class MySpringProgram {

    public static void main(String[] args) {
        new SpringApplicationBuilder(MySpringProgram.class)
                .profiles("profile1", "profile2")
                .run(args);
    }
}
SpringApplication app =new SpringApplication(Application.class);
    Properties props = new Properties();
    props.put("AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAM", "dev");
    app.setDefaultProperties(props);
    app.run(args);

我认为这段代码是更好的解决方案,因为它没有设置系统 属性