[英]How to Autowire conditionally in spring boot?
我創建了一個調度程序類
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");
}
}
在配置中,我放置了 @ConditionalOnProperty 注釋以在有條件的情況下啟用此功能。
@Bean
@ConditionalOnProperty(value = "jobs.enabled")
public TestSchedulderNew testSchedulderNew() {
return new TestSchedulderNew();
}
現在在控制器中,我創建了“stopScheduler”方法來停止那些調度程序,在這個控制器中我已經自動裝配了 TestSchedulderNew 類
@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";
}
}
現在的問題是,如果條件屬性為假,那么我得到以下異常
Field testSchedulderNew in com.sbill.app.web.rest.TestCont required a bean of type 'com.sbill.app.schedulerJob.TestSchedulderNew
如果真的一切正常,
我們有沒有辦法解決這個問題?
您可以在stopScheduler
方法中使用@Autowired(required=false)
和 null 檢查。
@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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.