Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I autowire a Spring TaskExecutor created thread?
    primarykey
    data
    text
    <p>According to <a href="http://static.springsource.org/spring/docs/3.0.4.RELEASE/reference/html/scheduling.html" rel="noreferrer">Spring's documentation</a> the way to use the TaskExecutor is as follows:</p> <pre><code>import org.springframework.core.task.TaskExecutor; public class TaskExecutorExample { private class MessagePrinterTask implements Runnable { private String message; public MessagePrinterTask(String message) { this.message = message; } public void run() { System.out.println(message); } } private TaskExecutor taskExecutor; public TaskExecutorExample(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void printMessages() { for(int i = 0; i &lt; 25; i++) { taskExecutor.execute(new MessagePrinterTask("Message" + i)); } } } </code></pre> <p>However, if MessagePrinterTask has autowired dependencies they will not be configured by Spring because we are instantiating our bean outside of Spring's context (at least that's how I understand it) even though Spring will provide the actual thread creation. <em>If MessagePrinterTask were to have autowired dependencies how do we get Spring to recognize them?</em> I tried the following modified example to no avail (and yes, autowiring is enabled properly):</p> <pre><code>import org.springframework.core.task.TaskExecutor; public class TaskExecutorExample { @Component private class MessagePrinterTask implements Runnable { @Autowired private autoWiredDependency; public void run() { autoWiredDependency.doNotThrowNullPointerExceptionPlease(); } } private TaskExecutor taskExecutor; public TaskExecutorExample(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void printMessages() { for(int i = 0; i &lt; 25; i++) { taskExecutor.execute(new MessagePrinterTask()); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload