79554345

Date: 2025-04-04 02:31:12
Score: 0.5
Natty:
Report link

Use a Map<String, Job> injection pattern and dynamically select based on config values

Spring can inject all beans of type Job into a Map<String, Job>, where the bean name is the key.

This allows you to use configuration properties like job1.name and job2.name to look up the right bean at runtime, without relying on multiple conditional bean definitions.

1. Define jobs as regular beans with specific names

@Configuration
public class MyConfiguration {

    @Bean("jobA")
    public Job jobA() {
        return new JobA();
    }

    @Bean("jobB")
    public Job jobB() {
        return new JobB();
    }

    @Bean("jobC")
    public Job jobC() {
        return new JobC();
    }

    @Bean
    public JobExecutor jobExecutor(
            Map<String, Job> jobMap,
            @Value("${job1.name}") String job1Name,
            @Value("${job2.name}") String job2Name) {

        Job job1 = jobMap.get(job1Name);
        Job job2 = jobMap.get(job2Name);

        return new JobExecutor(job1, job2);
    }
}

2. Your JobExecutor class

public class JobExecutor {

    private final Job job1;
    private final Job job2;

    public JobExecutor(Job job1, Job job2) {
        this.job1 = job1;
        this.job2 = job2;
    }

    public void execute() {
        job1.foo();
        job2.foo();
    }
}

3. Your application.properties

job1.name=jobA
job2.name=jobB

No need for @ConditionalOnExpression or @ConditionalOnProperty on every bean

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @ConditionalOnExpression
  • User mentioned (0): @ConditionalOnProperty
  • Low reputation (1):
Posted by: Vijay