How to Autowire conditionally in spring boot?

可紊 提交于 2020-06-16 03:44:19

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/57656119/how-to-autowire-conditionally-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!