SpringFramework—3、ClassPathXmlApplicationContext

概要

ClassPathXmlApplicationContext是spring framework的IoC容器的重要组成部分。如果你想使用Xml文件来完成Spring的相关配置,由于我们经常会将这样的xml配置文件放置在工程的资源目录下,所以这个类也是我们最常用的。

初始化

首先我们查看如下代码

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring.xml");

上面的代码,告诉ClassPathXmlApplicationContext类,使用名为application.xml的配置文件初始化IoC容器,那么去哪里寻找application.xml文件呢?答案是,去classpath中寻找。

我们编写相关spring工程的时候,通常会使用如下的目录结构来存放配置文件,所以指定的地址为:

spring/spring.xml

但是这个地址隐藏了classpath的信息,也可以改为:

classpath:spring/spring.xml

那么如果是很多个spring的配置文件,我们也可以使用通配符

classpath:spring/*.xml

使用占位符(PlaceHolder)

如果,我们需要使用外部的参数或者属性来管理spring的配置地址,那么我们就需要使用占位符来配置文件的路径。

例如,我们在运行中传入参数来管理spring配置文件的路径,或都通过系统属性设置,如下:

1、通过代码设置属性值(也可以在运行时,可以为java命令设置运行参数的方式设置),示例

System.setProperty("spring_config_file_name", "classpath:spring/*.xml");

ApplicationContext ctx = 
     new ClassPathXmlApplicationContext("${spring_config_file_name}");

2、通过开发工具设置系统属性

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注