Analysis of spring mvc configuration file

There are usually two configuration files in a spring MVC project, spring-servlet.xml and applicationContext.xml. The following configurations usually appear:

1. <context:annotation-config />

Its role is implicit Register the four BeanPostProcessors
- AutowiredAnnotationBeanPostProcessor,
- CommonAnnotationBeanPostProcessor,
- PersistenceAnnotationBeanPostProcessor, - RequiredAnnotationBeanPostProcessor with the Spring container  . Its function is that if you want to use the annotation in the program, you must first register the corresponding class of the annotation, as shown in the following figure: Dependent class annotations CommonAnnotationBeanPostProcessor @Resource, @PostConstruct, @PreDestroy PersistenceAnnotationBeanPostProcessor @PersistenceContext AutowiredAnnotationBeanPostProcessor @Autowired RequiredAnnotationBeanPostProcessor @Required Of course You can also register yourself:










<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

2. <context:component-scan base-package= The "com.*" >

<context:component-scan/> configuration item not only enables the scanning of class packages to implement annotation-driven bean definitions, but also enables annotation-driven automatic injection (that is, implicitly in the Internally registered AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor), so when using <context:component-scan/>, <context:annotation-config/> can be removed.

There is a more interesting question here, that is, whether scanning needs to be configured in both configuration files, I have done several tests:


(1) Only configure the following in applicationContext.xml
<context:component-scan base-package ="com.login" />
starts normally, but any request will not be intercepted, in short, @Controller fails

(2) only in spring-servlet.


(3) The above information is configured in both applicationContext.xml and spring-servlet.xml. The
startup is normal, the request is normal, and the transaction is invalid, and cannot be rolled back

(4) The configuration in applicationContext.xml is as follows
<context:component-scan base- package="com.login" />
is configured as follows in spring-servlet.xml
<context:component-scan base-package="com.sohu.login.web" />
At this time, the startup is normal, the request is normal, and things are normal .

Conclusion: In spring-servlet.xml, you only need to scan all classes annotated with @Controller, and you can scan all other classes annotated with @Controller in applicationContext (you can also filter out classes annotated with @Controller).

3. <mvc:annotation-driven />
It will automatically register DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326766377&siteId=291194637
Recommended