有没有办法根据应用程序属性使@EnableScheduling有条件?也可以根据属性禁用控制器吗?
我想要实现的是使用相同的Spring启动应用程序来处理Web请求(但不能在同一台计算机上运行计划任务),并在后端服务器上安装相同的应用程序以仅运行计划任务.
我的应用看起来像这样
@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 */
   }
}
我解决了这个问题,这是我今后所做的工作:
-
 @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
You can annotate a bean injection like this:
@Bean
@ConditionalOnProperty(prefix = "your.property", name = "yes", matchIfMissing = true)
public void doSomeBackendJob() {
       /* job implementation here */
}
Bonus: Since you want to run different things in different machines, i.e., you will deploy the same app with different configurations, you could use spring profiles, if that's the case you can annotate a class or method like this:
@Component
@Profile({ Constants.SPRING_PROFILE_PRODUCTION, Constants.SPRING_PROFILE_TEST })
public class TheClass{...}
我最终创建了一个单独的 @Configuration 类来进行调度,并使用 @ConditionalOnProperty 注释来切换调度
@Configuration
@EnableScheduling
@ConditionalOnProperty(prefix = "scheduling", name="enabled", havingValue="true", matchIfMissing = true)
public class SchedulerConfig {
}
然后在我的 application.yml 文件中添加
scheduling:
  enabled: true
| 归档时间: | 
 | 
| 查看次数: | 5610 次 | 
| 最近记录: |