Spring 配置文件说明

Spring MVC项目中通常会有二个配置文件,sprng-servlet.xml和applicationContext.xml二个配置文件,本文主要总结<context:component-scan>的一点说明。

<context:component-scan>标签主要实现了对类包扫描以实现注释驱动bean的作用,同时还启用了注释驱动自动注入的功能。

本标签(扫描)是否需要再两个配置文件中都配置一遍,下边有几种测试结果:

1,只在applicationcontext.xml中配置如下:

<context:component-scan base-package="com.a.frame,com.a.hmss,com.a.servpack">
启动正常,但任何请求都不会被拦截,@controller失效

2.只在spring-Servlet.xml中配置上述配置

启动正常,请求也正常,但是事物失效,不能完成回滚操作

3.两个文件都配置上述操作

启动正常,请求也正常,但是事物失效,不能完成回滚操作

4.在applicationcontext.xml中配置如下

<context:component-scan base-package="com.sesxh.frame,com.sesxh.hmss,com.sesxh.servpack">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

在spring-Servlet.xml中配置如下配置

<context:component-scan base-package="com.sesxh.hmss" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /><!-- z:mvc层只负责扫描@Controller -->
	</context:component-scan
结论:在spring-servlet.xml中只需要扫描所有带@Controller注解的类,在applicationContext中可以扫描所有其他带有注解的类(也可以过滤掉带@Controller注解的类)。


猜你喜欢

转载自blog.csdn.net/qq_33160365/article/details/79030215