The article directories

      • Child containers can refer to beans in the parent container, but the parent container cannot refer to beans in the child container
      • Processing mode (separate scan and two extremes)
      • The end of the

Child containers can refer to beans in the parent container, but the parent container cannot refer to beans in the child container

Spring and SpringMVC containers have a parent-child relationship. Spring is the parent container and SpringMVC is the child container. The child container can refer to beans in the parent container, and the parent container cannot refer to beans in the child container. So you can inject @Service, @Component, @repository beans into @Controller, but not the other way around.

Why should @Service, @Repository, @Component and @Controller be configured separately? Scan Controlller beans (@Controller) in the SpringMVC configuration file, and all beans except Controller (@Service, @Repository, @Component, etc.) in the Spring configuration file.

Processing mode (separate scan and two extremes)

1. Extreme: using only Spring to scan all beans in the configuration file, the answer is no.

Reasoning: SpringMVC will only look for Controller in its own context when matching the mapping between Controller and URL. Because all controllers are in the Spring container, SpringMVC could not find the Controller object and reported a 404 error. (In addition, the @Controller Bean can be injected into the @Service Bean, since both are in the Spring container, and the @Controller Bean can be injected by Spring.)

2. The first extreme change: Spring scans all beans and SpringMVC scans @Controller beans. The answer is yes.

There is no problem. The Controller maps to the URL. In addition, @Service Beans can inject @Controller beans (from the Spring container, not the SpringMVC container).

3. Extreme: Just use SpringMVC to scan all beans, and the answer is yes.

This is their own project configuration method, the use of no problem at all. So we don’t use a Spring container at all, we use a SpringMVC container. (Our project uses SpringMVC to scan all Spring annotations, excluding @mapper, which is ibatis annotations)

The end of the

The benefit of separate scanning is that it is easy to expand and integrate if the project needs to join Struts etc. Separate configuration enables both SpingMVC and Struts to use beans available in Spring. Beans in SpringMVC cannot be used in Struts if only SpringMVC scans are used.