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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With