How to Autowire conditionally in spring boot?

11,142

You can use @Autowired(required=false) and null check in stopScheduler method.

 @Autowired(required=false)
 private TestSchedulderNew testSchedulderNew;

 @GetMapping(value = "/stopScheduler")
 public String stopSchedule() {
     if (testSchedulderNew != null) {
         postProcessor.postProcessBeforeDestruction(testSchedulderNew, 
          SCHEDULED_TASKS);
         return "OK";
     }
     return "NOT_OK";
 }
Share:
11,142
user1731485
Author by

user1731485

Updated on June 03, 2022

Comments

  • user1731485
    user1731485 almost 2 years

    I have created one scheduler class

    public class TestSchedulderNew {
    
    @Scheduled(fixedDelay = 3000)
    public void fixedRateJob1() {
    System.out.println("Job 1 running");
    }
    
    @Scheduled(fixedDelay = 3000)
    public void fixedRateJob2() {
    System.out.println("Job 2 running");
    }
    }
    

    In configuration i have put @ConditionalOnProperty annotation to enable this on conditional purpose.

     @Bean
    @ConditionalOnProperty(value = "jobs.enabled")
    public TestSchedulderNew testSchedulderNew() {
    return new TestSchedulderNew();
    }
    

    Now in controller, i have created "stopScheduler" method to stop those scheduler , in this controller i have autowired TestSchedulderNew class

     @RestController
     @RequestMapping("/api")
     public class TestCont {
    
    private static final String SCHEDULED_TASKS = "testSchedulderNew";
    
     @Autowired
     private ScheduledAnnotationBeanPostProcessor postProcessor;    /]
    
     @Autowired
     private TestSchedulderNew testSchedulderNew;
    
    
     @GetMapping(value = "/stopScheduler")
     public String stopSchedule(){
      postProcessor.postProcessBeforeDestruction(testSchedulderNew, 
       SCHEDULED_TASKS);
      return "OK";
      }
     }     
    

    Now the problem is if conditional property is false then i get below exception

       Field testSchedulderNew in com.sbill.app.web.rest.TestCont required a bean of type 'com.sbill.app.schedulerJob.TestSchedulderNew
    

    In case of true everything works fine,

    Do we have any option to solve this ?