2

I am trying to understand how to use @profiles in spring-batch. I created a java file with two classes in it:

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

in the main java class I am trying to set the profiles as follows:

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

I set the profile using an Environment variable as profile=local

When the program is executed, I get a null pointer exception which I think is not getting the profile correctly. How can I use profiles concept in Spring Batch? Will it be different in normal spring vs spring batch?

user3379502
  • 223
  • 4
  • 22

1 Answers1

3

As far as I understood, you have to set the profile before you create the ApplicationContext. Once the application contenxt is created, changing the profile will not have any influence.

From the SpringBoot documentation, chapter 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.

Hansjoerg Wingeier
  • 4,274
  • 4
  • 17
  • 25