我试图了解如何在 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 中使用配置文件概念?普通 Spring 与 Spring 批处理会有不同吗?
最佳答案
据我了解,您必须在创建 ApplicationContext 之前设置配置文件。一旦创建了应用程序上下文,更改配置文件将不会产生任何影响。
摘自 SpringBoot 文档,第 25.2 章
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html
Programmatically setting profiles
You can programmatically set active profiles by calling SpringApplication.setAdditionalProfiles(…) before your application runs. It is also possible to activate profiles using Spring’s ConfigurableEnvironment interface.
关于spring-batch - Spring 批处理中的型材,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33787824/