How do I autowire a Spring TaskExecutor created thread?

后端 未结 3 1077
北海茫月
北海茫月 2021-02-04 08:18

According to Spring\'s documentation the way to use the TaskExecutor is as follows:

import org.springframework.core.task.TaskExecutor;

public class TaskExecutor         


        
3条回答
  •  伪装坚强ぢ
    2021-02-04 08:45

    You can also use the @Async annotation.

    public class TaskExecutorExample {
    
        @Autowired
        private MessagePrinterTask task;
    
        public void printMessages() {
            for(int i = 0; i < 25; i++) {
                task.printMessage();
            }
        }
    }
    
    @Component
    public class MessagePrinterTask implements Runnable {
    
        @Autowired
        private String message;
    
        @Async
        public void printMessage() {
          System.out.println(message);
        }
    
    }
    

    Any call to printMessage() will be executed asynchronously using a default executor, which you can configure using the following in your Spring xml config.

    
    
    

提交回复
热议问题