gpt4 book ai didi

java - 如何在 Spring Boot 中有条件地 Autowiring ?

转载 作者:行者123 更新时间:2023-12-01 13:10:21 26 4
gpt4 key购买 nike

我创建了一个调度程序类

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();
}

现在在 Controller 中,我创建了“stopScheduler”方法来停止那些调度程序,在这个 Controller 中我已经 Autowiring
测试调度新类
 @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

如果真的一切正常,

我们有没有办法解决这个问题?

最佳答案

您可以使用 @Autowired(required=false)和空检查 stopScheduler方法。

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

关于java - 如何在 Spring Boot 中有条件地 Autowiring ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57656119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com