Spring MVC项目中通常会有二个配置文件,spring-servlet.xml和applicationContext.xml二个配置文件,通常会出现以下几个配置:
当然也可以自己进行注册:
CommonAnnotationBeanPostProcessor @Resource 、@PostConstruct、@PreDestroy
PersistenceAnnotationBeanPostProcessor @PersistenceContext
AutowiredAnnotationBeanPostProcessor @Autowired
RequiredAnnotationBeanPostProcessor @Required
AutowiredAnnotationBeanPostProcessor、
CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor、
RequiredAnnotationBeanPostProcessor
这4个BeanPostProcessor。其作用是如果你想在程序中使用注解,就必须先注册该注解对应的类,如下图所示:
依赖的类-注解:
在这里有一个比较有意思的问题,就是扫描是否需要在二个配置文件都配置一遍,我做了这么几种测试:
只在applicationContext.xml中配置如下
启动正常,但是任何请求都不会被拦截,简而言之就是@Controller失效
只在spring-servlet.xml中配置上述配置启动正常,请求也正常,但是事物失效,也就是不能进行回滚
在applicationContext.xml和spring-servlet.xml中都配置上述信息
启动正常,请求正常,也是事物失效,不能进行回滚
在applicationContext.xml中配置如下
结论:在spring-servlet.xml中只需要扫描所有带@Controller注解的类,在applicationContext中可以扫描所有其他带有注解的类(也可以过滤掉带@Controller注解的类)。另外可以在利用context:include-filter和context:exclude-filter
过滤不需要扫描的注解。
它会自动注册DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter