弹簧批次中的轮廓

时间:2015-11-18 18:40:14

标签: spring-batch profiles

我试图了解如何在spring-batch中使用@profiles。 我创建了一个包含两个类的java文件:

@Configuration
@Profile("nonlocal")
class NonLocalConfiguration {
}
and
@Configuration
@Profile("local")
class LocalConfiguration {
}

在主java类中我试图按如下方式设置配置文件:

AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
String run_env = System.getenv("profile");
System.out.println("run_env is: " + run_env);
context.getEnvironment().setActiveProfiles(run_env);
context.refresh();

我使用环境变量设置配置文件作为profile = local

当程序执行时,我得到一个空指针异常,我认为没有正确获取配置文件。如何在Spring Batch中使用配置文件概念?普通弹簧与弹簧批次会有所不同吗?

1 个答案:

答案 0 :(得分:3)

据我了解,您必须在创建ApplicationContext之前设置之前的配置文件。创建应用程序contenxt后,更改配置文件将不会产生任何影响。

从SpringBoot文档,第25.2章http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

  

以编程方式设置配置文件
  您可以以编程方式设置活动   通过在之前调用SpringApplication.setAdditionalProfiles(...)来配置文件   你的应用程序运行也可以使用激活配置文件   Spring的ConfigurableEnvironment接口。