本文博客地址:http://blog.csdn.net/soonfly/article/details/68500062 (转载请注明出处)
一、实例化上下文对象
从前面的例子可以看到,在代码中实例化上下文对象非常简单,如下面的例子:
ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-beans.xml");
FooService foo = (FooService) ctx.getBean("FooService");
几个常用的类:
ClassPathXmlApplicationContext:从类路径下的xml配置文件中加载上下文定义.
FileSystemXmlApplicationContext:读取文件系统下xml配置文件并加载
XmlWebApplicationContext:读取Web应用下的Xml配置文件并加载上下文定义
ClassPathXmlApplicationContext与FileSystemXmlApplicationContext两者的区别只是查找配置文件的起始路径不同,一个以classpath为当前路径,一个是直接用文件系统的当前路径,内部没有太大区别。
XmlWebApplicationContext同ClassPathXmlApplicationContext一样,只不过应用于WEB工程项目。
二、加载多个配置文件
开发中,我们经常以业务功能或业务分层的方式,定义不同的xml配置文件。
如何加载多个xml配置文件呢?可以这样:
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml","Spring-Connection.xml","Spring-ModuleA.xml"});
但是这种方法不易组织并且不好维护。
如果配置文件存在多个的情况下,推荐的加载配置文件的方式有以下几个:
1、指定总的配置文件去包含子的配置文件,然后只加载总的配置文件即可。
在总的配置文件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");
2、使用星号来匹配多个文件进行加载,文件名称要符合规律。 (推荐使用)
配置文件的名称如下:
applicationContext.xml
applicationContext-action.xml
applicationContext-service.xml
applicationContext-dao.xml
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext*.xml");
3、可以使用数组作为参数,一次性加载多个配置文件
String[] files={"applicationContext.xml","applicationContext-test.xml"};
ApplicationContext ac = new ClassPathXmlApplicationContext(files);
注意:自动装配功能和手动装配要是同时使用,那么自动装配就不起作用。
4、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);
本文博客地址:http://blog.csdn.net/soonfly/article/details/68500062 (转载请注明出处)