Spring Boot @EnableScheduling 有条件地 [英] Spring Boot @EnableScheduling conditionally

查看:52
本文介绍了Spring Boot @EnableScheduling 有条件地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法根据应用程序属性使@EnableScheduling 成为条件?也可以根据属性禁用控制器吗?

Is there a way to make @EnableScheduling conditional based on an application property? also is it possible to disable controllers based on properties too?

我想要实现的是使用相同的 Spring Boot 应用程序来处理 Web 请求(但不在同一台机器上运行计划任务),并且还在后端服务器上安装相同的应用程序以仅运行计划任务.

What I'm trying to achieve is to have the same spring boot application used to serve web requests (but not run scheduled tasks on the same machine), and also install the same app on backend servers to run only scheduled tasks.

我的应用看起来像这样

@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 */
   }
}

推荐答案

我解决了这个问题,以下是我所做的以供将来参考:

I Solved this, here is what I did for future reference:

  • 从我的应用中删除了 @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 文件中:

Also, to disable web server on the backend server, just add the following to the application.properties file:

spring.main.web_environment=false

这篇关于Spring Boot @EnableScheduling 有条件地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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