如何在春季启动时有条件地自动接线? [英] How to Autowire conditionally in spring boot?

查看:75
本文介绍了如何在春季启动时有条件地自动接线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个调度程序类

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

在配置中,我放置了@ConditionalOnProperty批注以有条件地启用此功能.

In configuration i have put @ConditionalOnProperty annotation to enable this on conditional purpose.

 @Bean
@ConditionalOnProperty(value = "jobs.enabled")
public TestSchedulderNew testSchedulderNew() {
return new TestSchedulderNew();
}

现在在控制器中,我创建了"stopScheduler"方法来停止那些调度程序,在该控制器中,我已自动接线 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";
  }
 }     

现在的问题是,如果条件属性为false,那么我将获得以下异常

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 ?

推荐答案

您可以在stopScheduler方法中使用@Autowired(required=false)和空值检查.

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

这篇关于如何在春季启动时有条件地自动接线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆