Java – send auto assembly tasks to spring taskexecutor

How can you have a class that implements runnable and submits it to the spring taskexecutor for automatic connection?

For example, I have a task:

public class MyTask implements Runnable {

    @Autowired private MyRepository myRepository;

    @Override
    public void run() {
        myRepository.doSomething();
    }
}

There is also a service that sends tasks to the spring taskexecutor:

@Service
public class MyService {

    @Autowired private TaskExecutor taskExecutor;

    public void someMethod() {

        MyTask myTask = new MyTask();
        taskExecutor.execute(myTask);

    }

}

I know that these fields are not automatically wired because mytask is instantiated using the new mytask () But how to solve this problem? Should I access spring's ApplicationContext and create beans from it? How do you do this in a web application environment?

thank you!

Solution

There are at least two good ways to use spring 1、 @ configurable comment Using this means a dependency on AspectJ, but it will allow you to inject beans that are not managed by spring (that is, you are using new operators) This involves annotating mytask with @ configurable and adding a few lines to the spring configuration mentioned in the link

@Configurable
public class MyTask implements Runnable { ... }

@Service
public class MyService {
   @Autowired private TaskExecutor taskExecutor;

   public void someMethod() {

     // AspectJ would jump in here and inject MyTask transparently
     MyTask myTask = new MyTask();
     taskExecutor.execute(myTask);

}

}

The second approach will involve using spring's servicelocatorfactorybean function to create a prototype bean This is the best explanation in Javadoc, but in this case, you will inject a taskfactory into your @ service annotation class, just like any other bean, and then perform the following operations:

@Service
public class MyService {
  @Autowired private TaskExecutor taskExecutor;
  @Autowired private MyRepository myRepository;
  @Autowired private TaskFactory taskFactory;


public void someMethod() {
    MyTask myTask = taskFactory.getTask("myTask")
    taskExecutor.execute(myTask);
}

}

Mytask has been injected into your repository, and you can configure it in XML Mapping I use these two methods every day, but I prefer the second method because it is easier to read and keeps developers honest by ensuring that developers do not do things that are not easy to test. Frankly, it is more clear to casual observers

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>