ContextLoaderListener和ContextConfigLocation详解

ContextLoaderListener

在Spring中ContextLoaderListener实现了ServletContentListener类,该类可以作为Listener使用。

在启动Tomcat的时候,会自动装载ApplicationContext的配置信息,如果没有设置contextConfigLocation的初始参数则会使用默认参数WEB-INF路径下的application.xml文件。

如果需要自定义读取多个配置文件或者修改默认路径,在web.xml中设置如下即可:

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:applicationContext.xml</param-value>
</context-param>

ContextLoaderListener会读取这些XML文件并产生WebApplicationContext对象,然后将这个对象放置在ServletContext的属性里,这样我们只要可以得到Servlet就可以得到WebApplicationContext对象,并利用这个对象访问spring 容器管理的bean。

ContextConfigLocation

contextConfigLocation定义了要装入的 Spring 配置文件。

首先与Spring相关的配置文件必须要以"applicationContext-"开头,要符合约定优于配置的思想,这样在效率上和出错率上都要好很多。

把Spring配置文件都放在一个统一的目录下,如果项或者分模块建目录。

  • 注意

web.xml中

classpath:只会到你的class路径中查找找文件;

classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找.

猜你喜欢

转载自blog.csdn.net/ouzhuangzhuang/article/details/82849466