I have defined the following Spring boot application:
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run(args);
}
public void run(String... args) throws Exception {
Thread.currentThread().join();
}
}
I also have a package of workers (i.e. could be classes which implements Runnable
). They are supposed to run indefinitely.
What is the "Spring way" to run them? (and doing so automatically, without explicitly knowing them)
Thanks
and doing so automatically, without explicitly knowing them
There's no mechanism to automatically run some Runnable
s from a certain place. You need to find a way to inform Spring about these classes.
Three common scenarios:
ApplicationRunner
and CommandLineRunner
.You either congregate Runnable
s and wrap them up into an [Application|CommandLine]Runner
which should be a bean (e.g. @Bean
, @Component
, etc) or make each Runnable
a separate [Application|CommandLine]Runner
.
TaskExecutor
.You inject a TaskExecutor
and give it previously gathered Runnable
s.
TaskScheduler
.You inject a TaskScheduler
and give it previously gathered Runnable
s, plus a trigger.
More details: Task Execution and Scheduling
You could (1) have your classes that implement Runnable be annotated with @Component, so that Spring can find them. You can then (2) write a WorkManager, annotated with @Service, with an @Autowired List - which Spring would initialize with a list instances of all your classes from (1). And could (3) write a @PostConstruct method in your WorkManager that would iterate over that list of Runnables, and pass each one to a TaskExecutor to run...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With