我想执行一个Java类(其中包含Java线程我想执行)春天开机启动后。我最初的代码:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这里是我是要在开始执行的代码:
public class SimularProfesor implements Runnable{
// Class atributes
// Constructor
public SimularProfesor() {
//Initialization of atributes
}
@Override
public void run() {
while(true) {
// Do something
}
}
}
我怎样才能把这个主题?这是我应该做的事:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// Call thread (constructor must be executed too)
}
}
各地不要惹线程自己。春季(也是普通的Java),有一个很好的抽象。
首先创建类型的bean的TaskExecutor
配置中的
@Bean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor(); // Or use another one of your liking
}
然后创建一个CommandLineRunner
(虽然ApplicationListener<ContextRefreshedEvent>
也将工作)来安排你的任务。
@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
return new CommandLineRunner() {
public void run(String... args) throws Exception {
executor.execute(new SimularProfesor());
}
}
}
你当然可以也使弹簧管理自己的类。
这一优势是Spring还将清理你的线程,你不必去想它自己。我用CommandLineRunner
在这里,因为所有的豆类都豆初始化后,将执行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句