Spring学习 之实例化上下文对象及加载多个配置文件

mac2024-05-13  33

文章目录

实例化上下文对象加载多个配置文件方式一方式二方式三方式四

实例化上下文对象

在代码中实例化上下文对象非常简单,如下面的例子:

ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-beans.xml"); FooService foo = (FooService) ctx.getBean("FooService");

几个常用的实例化上下文的类:

ClassPathXmlApplicationContext:从类路径下的xml配置文件中加载上下文定义FileSystemXmlApplicationContext:读取文件系统下xml配置文件并加载XmlWebApplicationContext:读取Web应用下的Xml配置文件并加载上下文定义AnnotationConfigApplicationContext:基于Java的配置类加载Spring的应用上下文

ClassPathXmlApplicationContext与FileSystemXmlApplicationContext两者的区别只是查找配置文件的起始路径不同,一个以classpath为当前路径,一个是直接用文件系统的当前路径,内部没有太大区别。 XmlWebApplicationContext同ClassPathXmlApplicationContext一样,只不过应用于WEB工程项目。

加载多个配置文件

开发中,我们经常以业务功能或业务分层的方式,定义不同的xml配置文件。

方式一

ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"Spring-Common.xml","Spring-Connection.xml","Spring-ModuleA.xml"});

但是这种方法不易组织并且不好维护(不推荐)。

方式二

指定总的配置文件去包含子的配置文件,然后只加载总的配置文件即可。 在总的配置文件applicationContext.xml中使用import标签进行子文件包。

总配置文件applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <import resource="common/Spring-Common.xml"/> <import resource="connection/Spring-Connection.xml"/> <import resource="moduleA/Spring-ModuleA.xml"/> </beans>

代码中加载配置文件:

ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");

方式三

使用星号来匹配多个文件进行加载,文件名称要符合规律。 (推荐使用)

配置文件的名称如下: applicationContext.xml applicationContext-action.xml applicationContext-service.xml applicationContext-dao.xml

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext*.xml");

方式四

JavaConfig配置的情况下:可单独创建一个AppConfig.java,然后将其他的配置导入到AppConfig.java中

import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({ CustomerConfig.class, SchedulerConfig.class }) public class AppConfig { }

这样,加载时,只需要加载AppConfig.java即可

ApplicationContext context =   new AnnotationConfigApplicationContext(AppConfig.class);
最新回复(0)