0915240 0915240 - 28 days ago 11
Java Question

SpringMVC : <context:component-scan /> and <mvc:annotation-driven> must in the same context?

ApplicationContext is a parent of WebApplicationContext .

But why and must palce in the same context then it will works ?

Here is my explain:

=============

I config my applicationConext.xml like this :

<context:component-scan base-package="com.github" />
<mvc:annotation-driven />


and none similar settings in dispatcher-servlet.xml.

It works!!!

===========

I config my dispatcher-servlet.xml like this :

<context:component-scan base-package="com.github" />
<mvc:annotation-driven />


and none similar settings in applicationConext.xml.

It also works!!!

==========

BUT , If i put
<context:component-scan base-package="com.github" />
in applicationConext.xml and
<mvc:annotation-driven />
in dispatcher-servlet.xml OR put
<context:component-scan base-package="com.github" />
in dispatcher-servlet.xml and
<mvc:annotation-driven />
in applicationConext.xml.

It doesnot work!!! return httpStatus 404,not found,that means it doesnot mapping to the Controller.

ApplicationContext is a parent of WebApplicationContext , the child context shoud inherit from the parent conext , so I thought the settings can separate in different context but not the same one !

Am I wrong ? Please anybody could answer me , thx !

Answer

In Spring you have the root application context which is an WebApplicationContext and at least one child WebApplicationContext, although you could have multiple DispatcherServlets with corresponding WebApplicationContexts. Those are different contexts, although the DispatcherServlet's WebApplicationContext is a child of the root application context. This means that the child context has access to all the beans of the root application context, but still they are two different contexts.

Now each context is constructed separately using the corresponding configuration files. Thus if you only specify <context:component-scan /> in one package and <mvc-annoation-driven /> in another, then when constructing the one context it will make a component-scan, but it will not register any controller related annotations since you did not enable them with <mvc-annoation-driven /> in the same config file. Now in the other context, controller related annoations are enabled, but no components are ever scanned. This is why no mappings are found.

This is also why common configuration that would be used by multiple DispatcherServlets is configured in the root application context while controller related configuration is configured in the corresponding web application contexts.

Comments