Note that there are some explanatory texts on larger screens.

plurals
  1. POInject dependency from background tasks
    text
    copied!<p>I am new to spring and I am trying to figure out how to Autowire an object to a controller. The object is created at runtime from a task that is started and stopped using a ServletContextListener. How do I tell the spring application context about this object?</p> <p><strong>More Details</strong></p> <p>My background task is started with the code below. I'd like the <code>alertServer</code> object wired to a controler. Can I modify this class to do that?</p> <pre><code>@WebListener public class ExecutorContextListener implements ServletContextListener { private static Logger log = Logger.getLogger(ExecutorContextListener.class); Thread backgroundThread; AlertServer alertServer; @Override public void contextInitialized(ServletContextEvent event) { // Start the AlertServer alertServer = new AlertServer(); backgroundThread = new Thread(alertServer, "AlertServer"); backgroundThread.start(); } @Override public void contextDestroyed(ServletContextEvent event) { alertServer.stop(); try { backgroundThread.join(); } catch (InterruptedException e) { log.error("contextDestroyed Exception", e); } } } </code></pre> <p><strong>UPDATE</strong></p> <p>The comments and answers provided were very helpful in finding a solution. With the info provided by Sotirios Delimanolis, and Dave Newton I realized that now that I'm building my solution on top of Spring, I don't really need to use a ServletContextListener in the first place. All I really wanted to do was start a background thread that is available to Spring controllers, so I put this code in my servlet-context.xml and I am up and running.</p> <pre><code>&lt;beans:bean id="alertServer" class="com.springmvcproj.AlertServer"&gt; &lt;beans:property name="serverPort" value="56543" /&gt; &lt;/beans:bean&gt; &lt;beans:bean id="AlertServerThread" class="java.lang.Thread" init-method="start"&gt; &lt;beans:constructor-arg ref="alertServer"/&gt; &lt;/beans:bean&gt; </code></pre>
 

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