<context:component-scan/>
該xml配置作用是啟動Spring的組件掃描功能,自動掃描base-package指定的包及其子文件下的java文件,如果掃描到有@controller、@Service、@Repository、@Component等注解的java類,就會將這些類注冊為bean。指定的包可以有多個,用分號隔開。
如果指定了<context:component-scan/>就不用指定<context:annotation-config/>,前者包含后者。使用示例如下:
<context:component-scan base-package="com.ouym.base" use-default-filters="false"><!-- base-package 如果多個,用“,”分隔 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
base-package指定需要掃描的包,include-filter指定需要掃描的注解,上述配置的意思是掃描com.ouym.base包下的@controller注解的java文件。
而<context:annotation-config/>的實際作用是向spring容器注入以下幾個類:AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 及RequiredAnnotationBeanPostProcessor 四個beanPostProcessor。這些類的作用主要是使一些注解生效,詳細請自行查閱。
<mvc:annotation-driver/>
在spring中一般采用@RequestMapping注解來完成映射關系,要想使@RequestMapping注解生效必須向上下文中注冊DefaultAnnotationHandlerMapping和一個AnnotationMethodHandlerAdapter實例,這兩個實例分別在類級別和方法級別處理。而annotation-driven配置幫助我們自動完成上述兩個實例的注入。
該注解要和掃描controller的注解一起放在spring主配置文件。