Autowiring Tasks sent to Spring TaskExecutor

前端 未结 2 1676
情话喂你
情话喂你 2021-02-05 14:30

How can you have a class that implements Runnable and submitted to springs TaskExecutor autowired?

For example, I have a Task:

public class MyTask implem         


        
2条回答
  •  醉梦人生
    2021-02-05 15:07

    try

    public class MyTask implements Runnable {
        private MyRepository myRepository;
    
        public MyTask(MyRepository myRepository) {
             this.myRepository = myRepository;
        }
    
        @Override
        public void run() {
            myRepository.doSomething();
        }
    }
    
    @Service
    public class MyService {
        @Autowired private TaskExecutor taskExecutor;
        @Autowired private MyRepository myRepository;
    
    
        public void someMethod() {
            MyTask myTask = new MyTask(myRepository);
            taskExecutor.execute(myTask);
        }
    }
    

    or you can declare MyTask's scope = "prototype" and change MyService as

    @Service
    public class MyService {
        @Autowired private ApplicationContext ctx;
    
        public void someMethod() {
            MyTask myTask = ctx.getBean(MyTask.class);
            taskExecutor.execute(myTask);
        }
    }
    

提交回复
热议问题