Rajesh Khore
Rajesh Khore

Reputation: 375

How to Autowire conditionally in spring boot?

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 the 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 the controller, I have created "stopScheduler" method to stop this 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 the conditional property is false then I get the 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?

Upvotes: 24

Views: 26213

Answers (1)

shazin
shazin

Reputation: 21883

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";
 }

Upvotes: 36

Related Questions