Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a ContextLoaderListener in accordance with DispatchServlet

I want to use both ContextLoaderListener (so that I can pass Spring Beans to my servlet) as well as DispatchServlet (Spring MVC). However, currently I have to pass init param to these both class initializer:

<param-name>contextConfigLocation</param-name>
<param-value>
    /WEB-INF/spring/app-config.xml
</param-value>

So, I use the same xml for these both classes. Wonder if it would lead to my beans being initialized twice? If yes, how would I do to avoid that?

like image 709
Phương Nguyễn Avatar asked Apr 06 '10 06:04

Phương Nguyễn


2 Answers

For both ContextLoaderListener and DispatcherServlet, the contextConfigLocation parameter is optional.

ContextLoaderListener defaults to /WEB-INF/application.xml, DispatcherServlet defaults to /WEB-INF/servletname-servlet.xml.

If you set these parameters explicitly, you should not set them to the same value. The ContextLoaderListener and DispatcherServlet should have contexts with different sets of bean definitions, since otherwise, as you say, the beans will be instantiated twice.

like image 69
skaffman Avatar answered Oct 21 '22 21:10

skaffman


to force DispatcherServlet initialization use context from ContextLoaderListener you should set contextConfigLocation as empty:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:spring-context.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
like image 6
mokshino Avatar answered Oct 21 '22 23:10

mokshino