Java – How do I load a Spring configuration based on command line arguments?

How do I load a Spring configuration based on command line arguments?… here is a solution to the problem.

How do I load a Spring configuration based on command line arguments?

I have several different @Configuration classes, each corresponding to a different Spring Batch job, i.e. there is a Job bean in each configuration, and every step, tasklet, etc. required for a given job exists in the same configuration as the class for that job. Example:

@Configuration
public class DemoJobConfiguration(JobBuilderFactory jobBuilderFactory) {
    @Bean
    public Job demoJob() {
        return jobBuilderFactory.get("demoJob").start(...). build();
    }
}

@Configuration
public class TestJobConfiguration(JobBuilderFactory jobBuilderFactory) {
    @Bean
    public Job testJob() {
        return jobBuilderFactory.get("testJob").start(...). build();
    }
}

The application is a command-line application. The first parameter is the name of the job to run. Retrieves the associated Job bean based on this parameter and executes it using JobLauncher. Example:

@Override
public void run(String... args) throws Exception {
    String jobName = args[0];
    Job job = prepareJob(jobName); gets the Job from the application context
    JobParameters jobParameters = prepareJobParameters(args); sets args[1], etc. to JobParameter objects
    JobExecution result = jobLauncher.run(job, jobParameters);
}

What I’m wondering is if there is a way to load only the configuration class using the @Conditional annotation (or other annotation) if args[0] is some value, e.g

@Configuration
@Conditional("\"testJob\".equals(args[0])")
public class TestJobConfiguration(JobBuilderFactory jobBuilderFactory) {
    ...
}

The advantage of this is that only beans related to running jobs are loaded into memory, while beans corresponding to other jobs are never loaded. This will be useful as more work is added to the project.

Can I load a configuration based on command-line arguments? Have you done it before? An hour of googling found no results, but I still wish there was a way to achieve this.

Solution

I found the answer to my own question.

Workaround:

  1. Contains a command-line argument in the form of –jobName=testJob. Spring boot automatically loads it into the environment ( https://docs.spring.io/spring-boot/docs/1.0.1.RELEASE/reference/html/boot-features-external-config.html )

  2. Use @ConditonalOnProperty Comment like this:

    @ConditionalOnProperty(value = “jobName”, havingValue = “testJob”)
    Public class TestJobConfiguration {

Related Problems and Solutions