Start thread at springboot application

后端 未结 2 1221
情深已故
情深已故 2020-12-24 06:15

I want to execute a java class (which contains a java thread I want to execute) after spring boot starts. My initial code:

@SpringBootApplication
public clas         


        
相关标签:
2条回答
  • 2020-12-24 06:59

    Don't mess around with threads yourself. Spring (and also plain Java) has a nice abstraction for that.

    First create a bean of the type TaskExecutor in your configuration

    @Bean
    public TaskExecutor taskExecutor() {
        return new SimpleAsyncTaskExecutor(); // Or use another one of your liking
    }
    

    Then create a CommandLineRunner (although an ApplicationListener<ContextRefreshedEvent> would also work) to schedule your task.

    @Bean
    public CommandLineRunner schedulingRunner(TaskExecutor executor) {
        return new CommandLineRunner() {
            public void run(String... args) throws Exception {
                executor.execute(new SimularProfesor());
            }
        }
    }
    

    You could of course make also your own class managed by spring.

    Advantage of this is that Spring will also cleanup the threads for you and you don't have to think about it yourself. I used a CommandLineRunner here because that will execute after all beans have bean initialized.

    0 讨论(0)
  • 2020-12-24 07:03
    • Main Class SpringBoot

      @SpringBootApplication
      @EnableAsync
      @Controller
      public class ...
      
      
    • Example Class Controler

      import javax.annotation.PostConstruct;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.ApplicationContext;
      import org.springframework.core.task.TaskExecutor;
      import org.springframework.stereotype.Component;
      
      @Component
      public class ExecutorBase {
      
          private static final Logger log = LoggerFactory.getLogger(ExecutorBase.class);
      
          @Autowired
          private TaskExecutor taskExecutor;
          @Autowired
          private ApplicationContext applicationContext;
      
          private Boolean debug = true;
      
          @PostConstruct
          public void atStartup() {
              ClasseTaskRunn classeTaskRunn = applicationContext.getBean(ClasseTaskRunn.class);
              taskExecutor.execute(classeTaskRunn );
              if (debug) {
                  log.warn("###### Startup ok");
              }
          }
      }
      
      
    • Example Class Task Runnable

      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Scope;
      import org.springframework.stereotype.Component;
      
      @Component
      @Scope("application")
      public class ClasseTaskRunn implements Runnable {
      
          private static final Logger log = LoggerFactory.getLogger(ClasseTaskRunn.class);
      
          @Autowired
          ClasseDAO classeDAO;
      
          @Override
          public void run() {
              longBackgorund();
          }
      
          protected void longBackgorund() {
              while (test) {
                  if (debug) {
                      log.warn("###### DEBUG: " ... );
                  }
      
                  try {
                      Thread.sleep(10000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
      }
      
      
    0 讨论(0)
提交回复
热议问题