如何在 spring 启动时有条件地自动装配?
How to Autowire conditionally in spring boot?
我创建了一个调度器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");
}
}
在配置中,我添加了@ConditionalOnProperty 注释以在有条件的情况下启用它。
@Bean
@ConditionalOnProperty(value = "jobs.enabled")
public TestSchedulderNew testSchedulderNew() {
return new TestSchedulderNew();
}
现在在控制器中,我创建了 "stopScheduler" 方法来停止那些调度程序,在这个控制器中我已经自动装配
测试调度新 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";
}
}
现在的问题是,如果条件 属性 为假,那么我将低于异常
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";
}
我创建了一个调度器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");
}
}
在配置中,我添加了@ConditionalOnProperty 注释以在有条件的情况下启用它。
@Bean
@ConditionalOnProperty(value = "jobs.enabled")
public TestSchedulderNew testSchedulderNew() {
return new TestSchedulderNew();
}
现在在控制器中,我创建了 "stopScheduler" 方法来停止那些调度程序,在这个控制器中我已经自动装配 测试调度新 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";
}
}
现在的问题是,如果条件 属性 为假,那么我将低于异常
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";
}