Reputation: 2057
I am working on scheduling library. I am using @EnableScheduling
to enable and run schedulers in Spring boot. There are many beans/components that I need in my scheduler. But I want to create the beans only if @EnableScheduling
is present in the application. How can I achieve that?
Upvotes: 0
Views: 438
Reputation: 44665
If you take a look at what @EnableScheduling
does, you'll see that it imports the SchedulingConfiguration
configuration. Within this configuration class, a single bean is defined, called ScheduledAnnotationBeanPostProcessor
.
This means that if you use conditionals to check for the existence of the ScheduledAnnotationBeanPostProcessor
bean, you can define beans that are only created when @EnableScheduling
is present.
For this purpose, we can use the @ConditionalOnBean
annotation. For example:
@Bean
@ConditionalOnBean(ScheduledAnnotationBeanPostProcessor.class)
public CommandLineRunner appRunner() {
return args -> logger.info("Scheduling is enabled!");
}
Upvotes: 2