有条件的Spring Boot @EnableScheduling

有没有一种方法可以根据应用程序属性使@EnableScheduling有条件?也可以基于属性禁用控制器吗?

我要实现的目标是拥有用于服务Web请求的相同的Spring

Boot应用程序(但不能在同一台计算机上运行计划的任务),并且还要在后端服务器上安装同一应用程序以仅运行计划的任务。

我的应用看起来像这样

@SpringBootApplication

@EnableScheduling

@EnableTransactionManagement

public class MyApp {

public static void main(String[] args) {

SpringApplication.run(MyApp.class, args);

}

}

预定的工作样本如下所示

@Component

public class MyTask {

@Scheduled(fixedRate = 60000)

public void doSomeBackendJob() {

/* job implementation here */

}

}

回答:

我解决了这个问题,这是我以后做的参考:

  • 从我的应用中删除了@EnableScheduling批注
  • 添加了新的配置类和条件,以基于应用程序属性启用/禁用调度

--

 @Configuration

public class Scheduler {

@Conditional(SchedulerCondition.class)

@Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)

@Role(BeanDefinition.ROLE_INFRASTRUCTURE)

public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {

return new ScheduledAnnotationBeanPostProcessor();

}

}

和条件班

public class SchedulerCondition implements Condition {

@Override

public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

return Boolean.valueOf(context.getEnvironment().getProperty("com.myapp.config.scheduler.enabled"));

}

}

另外,要在后端服务器上禁用Web服务器,只需将以下内容添加到application.properties文件中:

spring.main.web_environment=false

以上是 有条件的Spring Boot @EnableScheduling 的全部内容, 来源链接: utcz.com/qa/406396.html

回到顶部