views:

232

answers:

1

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?

+2  A: 

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.

skaffman
So, there's no way for these two to share the same set of beans?
Phương Nguyễn
@Phuong: The servlet's beans will have access to the beans in the context loaded by the listener. The contexts form a parent-child relationship. The beans are "owned" by the parent, but visible to the child
skaffman
Hmm, I read one of your post here: http://stackoverflow.com/questions/1464881/defaultannotationhandlermapping-via-contextloaderlistener-instead-of-dispatcherse, and the problem was explained much cleaner. I will try to see whether I can avoid duplicating my beans. Thanks.
Phương Nguyễn