मेरी धारियों ऐप्लिकेशन में मैं निम्नलिखित वर्ग को परिभाषित। मैं SomeService
और AnotherService
को MyServletListener
में लागू करने वाले बीन्स इंजेक्ट करना चाहता हूं, क्या यह संभव है?निर्भरता इंजेक्षन सर्वलेट श्रोता
12
A
उत्तर
23
कुछ इस तरह काम करना चाहिए:
public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
@Autowired
private SomeService someService;
@Autowired
private AnotherService anotherService;
public void contextInitialized(ServletContextEvent sce) {
WebApplicationContextUtils
.getRequiredWebApplicationContext(sce.getServletContext())
.getAutowireCapableBeanFactory()
.autowireBean(this);
}
...
}
आपका श्रोता के बाद घोषित किया जाना चाहिए वसंत के ContextLoaderListener
web.xml
में।
10
SpringBeanAutowiringSupport
कक्षा का उपयोग करने के लिए थोड़ा छोटा और सरल है।
तुम सब करने की है की तुलना में इस प्रकार है:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
तो axtavt से उदाहरण का उपयोग:
public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
@Autowired
private SomeService someService;
@Autowired
private AnotherService anotherService;
public void contextInitialized(ServletContextEvent sce) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
...
}
+0
यह एक बहुत ही आसान तरीका है, और यह पूरी तरह से काम करता है। – Calabacin
@Don: 'contextInitalized (ServletContextEvent)' पर [ 'ServletContextListener'] (http परिभाषित किया गया है: //download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html#contextInitialized(javax.servlet.ServletContextEvent)) – ig0774
यह बहुत अच्छा काम करता है! – Nico
महत्वपूर्ण: web.xml ContextLoaderListener में MyServletListener से पहले लोड किया जाना चाहिए। – Nico