3

I am learning about Spring MVC and I have created one root web application context using the context listener. From what I have read this is used to declare beans such as service beans etc and the dispatcher servlets inherits from the root context.

I have added the component scan XML element in the root context. It scans all the packages including those with @Controller. So why doesn't the URL for the controller until I add another component scan in the dispatcher context? Would it be duplicate bean definitions? And is this even correct?

Should I add component scan in the root context only for the services packages etc. and then the component scan element in the dispatcher context only for the controller package?

Removed namspaces from context files.

From dispatcher context:

<beans>
    <!--<context:component-scan base-package="com.mycompany.controller"/>-->
    <mvc:annotation-driven/>    
</beans>

Root context:

<beans>
    <context:component-scan base-package="com.mycompany"/>
</beans>

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>defaultServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/webContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>defaultServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>
LuckyLuke
  • 47,771
  • 85
  • 270
  • 434

0 Answers0