问题
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
回答1:
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...
回答2:
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:
- Execute some code during the application startup: 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
.
- Execute some code at some point of time: TaskExecutor.
You inject a TaskExecutor
and give it previously gathered Runnable
s.
- Execute some code repeatedly: TaskScheduler.
You inject a TaskScheduler
and give it previously gathered Runnable
s, plus a trigger.
More details: Task Execution and Scheduling
来源:https://stackoverflow.com/questions/53363433/spring-boot-application-for-background-workers