【问题标题】:How to Autowire conditionally in spring boot?如何在弹簧靴中有条件地自动装配?
【发布时间】:2019-08-26 10:26:58
【问题描述】:

我创建了一个调度器类

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”方法来停止那些调度程序,在这个控制器中我已经自动连接 TestSchulderNew 类

 @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

如果是真的一切正常,

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

【问题讨论】:

    标签: java spring-boot dependency-injection autowired


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2021-08-05
      • 2012-10-18
      • 1970-01-01
      相关资源
      最近更新 更多