Make ServletContextListener spring aware

Rudziankoŭ :

I am plugging in Spring to existing Java EE web Application. I have following lines in my web.xml:

<listener>
    <listener-class>com.MyContextListener</listener-class>
</listener> 

And Following MyContextListener class?

public class MyContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
       //...
    }
}

What should I do to make MyContextListener be managed by Spring?


Edited:

My assumption is: Spring should create all servlets and all web app infrastructure so everything happened in contextInitialized method of MyContextListener should be somehow handled by Spring. How can I achieve, by implementing some interface I suppose. Correct me if I am wrong. Thanks!

Raf :

Well,

We had a similar scenario of configuring an exiting Jersey web services app to use Spring for dependency injection. Our Jersey webapp had extended ContextLoaderListener as follow

public class XServletContextListener extends ContextLoaderListener {
    ... 
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        super.contextInitialized(arg0);
        ....
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        super.contextDestroyed(arg0);
        ....
    }
} 

where ContextLoaderListener is

import org.springframework.web.context.ContextLoaderListener;

We included the jersey-spring bridge with all spring dependencies including applicationContext.xml as follow

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.xxx.*" />
    ....
    ....
</beans>

And obviously needed to make sure that XServletContextListener is included in the web.xml as follow

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>com.xxx.**.XServletContextListener</listener-class>
</listener>

Followed by servlet and its init-param values and servlet mapping. You can obviously adopt annotation config in place of xml confib in which case you would need to use WebListener annotation.

We use a variety of annotations such as

@Component for objects
@Service for services 
@Repository for DAOs
@Controller for controllers/resources 
@ContextConfiguration for tests

Everything is loaded and autowired by Spring framework.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=447900&siteId=1