SpringMVC的xml配置细节点
在springMVC配置中,一些配置用于处理对应的注解,以下为几点比较难以区分的配置:
- <context:annotation-config />
- <context:component-scan base-package=“com.xx.xx” />
- <mvc:annotation-driven />
<context:annotation-config />
-
作用
在Spring中配置**<context:annotation-config />**,它的作用是隐式的向Spring容器中注册以下几个处理器:AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor
-
AutowiredAnnotationBeanPostProcessor
此处理器主要是为**@Autowired**注解进行注册,如果需要用该注解就需要注册
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
-
CommonAnnotationBeanPostProcessor
此处理器主要是为**@PersistenceContext**注解进行注册,如果需要用该注解就需要注册
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
-
PersistenceAnnotationBeanPostProcessor
此处理器主要是为**@Required**注解进行注册,如果需要用该注解就需要注册
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
-
RequiredAnnotationBeanPostProcessor
此处理器主要是为**@Resource、@ PostConstruct、@ PreDestroy等**注解进行注册,如果需要用该注解就需要注册
<bean class="org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor"/>
<context:annotation-config /> 只能在已经注册过的bean起作用,也就是说,上述那些注解无法使用在未曾注册过的bean中。
<context:component-scan base-package=“com.xx.xx” />
-
作用
该配置的作用是让启动bean定义注解,也就是说,对在base-package指定的包中扫描在类上定义的注解,这样就不用传统的bean进行注册。
-
注意点
注意:<context:component-scan base-package=“com.xx.xx” />不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此当使用
<context:component-scan/>
后,就可以将<context:annotation-config/>
移除了。 -
支持的注解
- @Autowired
- @Component
- @Repository
- @Service
- @Controller
- @RestController,
- @ControllerAdvice,
- @Configuration
<mvc:annotation-driven />
-
作用
用于启动@Controller注解
-
注意点
要使用spring mvc中的@Controller注解,就必须要配置<mvc:annotation-driven />,否则org.springframework.web.servlet.DispatcherServlet无法找到控制器并把请求分发到控制器。