applicationContext not finding Controllers for Servlet context

后端 未结 3 483

I have a Spring web app with an applicationContext.xml and a dispatcher-servlet.xml configuration. I\'ve defined the in applic

3条回答
  •  失恋的感觉
    2020-12-01 04:38

    You are right - there are two different application contexts, the root application context loaded up by ContextLoaderListener (at the point the ServletContext gets initialized), and the Web Context (loaded up by DispatcherServlet), the root application context is the parent of the Web context.

    Now, since these are two different application contexts, they get acted on differently - if you define component-scan for your services in application context, then all the beans for the services get created here.

    When your Dispatcher servlet loads up it will start creating the Web Context, at some point(driven by it will create a mapping for your uri's to handler methods, it will get the list of beans in the application context(which will be the web application context, not the Root application Context) and since you have not defined a component-scan here the controller related beans will not be found and the mappings will not get created, that is the reason why you have to define a component-scan in the dispatcher servlets context also.

    A good practice is to exclude the Controller related beans in the Root Application Context:

    
        
    
    

    and only controller related one's in Web Application Context:

    
        
    
    

提交回复
热议问题