Phương Nguyễn
Phương Nguyễn

Reputation: 8905

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?

Upvotes: 5

Views: 7088

Answers (3)

devcodecc
devcodecc

Reputation: 121

Also can try this, --in bean context exclude controller scan

<context:annotation-config/>
<context:component-scan base-package="com.test.example">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

and in dispatcher servle context, scan only controller

<context:component-scan base-package="com.test.example"  use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<context:annotation-config/>

https://www.concretepage.com/spring/spring-component-scan-include-and-exclude-filter-example

Upvotes: 0

mokshino
mokshino

Reputation: 1493

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>

Upvotes: 6

skaffman
skaffman

Reputation: 403501

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.

Upvotes: 12

Related Questions