Why not manage controller in spring container

Spring container and spring MVC container

 

1. Question: why not use spring to manage all classes?

In our configuration of spring MVC, why does the controller not be directly managed by spring, but the spring MVC container should be managed separately

 

 

 

2. The relationship between spring container and spring MVC

Spring container is a parent-child relationship with spring MVC container. The child container can access the objects of the parent container, but the parent container can’t access the classes of the child container. If we scan all classes directly in the spring MVC configuration file and hand over service, Dao and controller to spring MVC for management, but if spring is used to manage contoller, it can’t access this class, because Co The ntoller is in the spring MVC container. If you configure spring to scan all classes directly, including controller, but do not configure spring MVC, the request sent by the server will have a 404 problem, because it can’t find the controller and spring can’t inject the controller

Example.
Configure in applicationContext-service.
<! -- Scan package to load Service implementation classes -->
<context:component-scan base-package="com.easybuy"></context:component-scan>
will scan for @Controller, @Service, @Repository, @Compnent

Springmvc.Xml does not scan.
Conclusion: springmvc. cannot provide services because there is no controller object in the springmvc subcontainer.

3. Why not directly SpringMVC.xml Scan all classes in?

In principle, we can leave the service, Dao and controller to spring MVC for management, and just let it scan all packages directly in the spring MVC configuration file. However, for the sake of future expansion, spring and spring MVC are configured separately, and spring manages the service, which is conducive to later expansion. Even if multiple struct2 are added in the future, the original configuration will not be affected


Read More: