有条件地弹簧启动@EnableScheduling

Bad*_*heh 10 java spring-boot

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

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

我的应用看起来像这样

@SpringBootApplication
@EnableScheduling
@EnableTransactionManagement
public class MyApp {

   public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
   }

}
Run Code Online (Sandbox Code Playgroud)

示例预定作业看起来像这样

@Component
public class MyTask {

   @Scheduled(fixedRate = 60000)
   public void doSomeBackendJob() {
       /* job implementation here */
   }
}
Run Code Online (Sandbox Code Playgroud)

Bad*_*heh 8

我解决了这个问题,这是我今后所做的工作:

  • 从我的应用程序中删除了@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

和条件类

public class SchedulerCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return Boolean.valueOf(context.getEnvironment().getProperty("com.myapp.config.scheduler.enabled"));
    }

}
Run Code Online (Sandbox Code Playgroud)

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

spring.main.web_environment=false
Run Code Online (Sandbox Code Playgroud)


imT*_*chu 7

You can annotate a bean injection like this:

@Bean
@ConditionalOnProperty(prefix = "your.property", name = "yes", matchIfMissing = true)
public void doSomeBackendJob() {
       /* job implementation here */
}
Run Code Online (Sandbox Code Playgroud)

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{...}
Run Code Online (Sandbox Code Playgroud)

  • `@ConditionalOnProperty` 不会影响 `@Scheduled` 方法,因为和所有条件一样,它只影响 bean 注册。有关更多详细信息,请参阅 javadoc:http://docs.spring.io/spring-framework/docs/4.3.2.RELEASE/javadoc-api/org/springframework/context/annotation/Conditional.html?is-external=true (3认同)

ash*_*rio 7

我最终创建了一个单独的 @Configuration 类来进行调度,并使用 @ConditionalOnProperty 注释来切换调度

@Configuration
@EnableScheduling
@ConditionalOnProperty(prefix = "scheduling", name="enabled", havingValue="true", matchIfMissing = true)
public class SchedulerConfig {

}
Run Code Online (Sandbox Code Playgroud)

然后在我的 application.yml 文件中添加

scheduling:
  enabled: true
Run Code Online (Sandbox Code Playgroud)