Spring -> 实例化上下文对象及加载多个配置文件

1. 读取配置文件

几个常用的类:

ClassPathXmlApplicationContext
从类路径下的xml配置文件中加载上下文定义. ,以classpath为当前路径

FileSystemXmlApplicationContext
读取文件系统下xml配置文件并加载 ,直接用文件系统的当前路径
ClassPathXmlApplicationContext区别只在于查找配置文件的起始路径不同

XmlWebApplicationContext
读取Web应用下的Xml配置文件并加载上下文定义
ClassPathXmlApplicationContext一样,只不过应用于WEB工程项目

AnnotationConfigApplicationContext
使用AnnotationConfigApplicationContext可以实现基于Java的配置类加载Spring的应用上下文。避免使用application.xml进行配置。相比XML配置,更加便捷

ApplicationContext ctx = new ClassPathXmlApplicationContext( "Application.xml");
//两种获取bean的方式
Order order = ctx.getBean("order", Order.class);
Order order = (Order) ctx.getBean("order");

2. 加载多个配置文件

1、数组方式加载
这种方法不易组织并且不好维护

String[] files={"applicationContext.xml","applicationContext-test.xml"};  
ApplicationContext context = new ClassPathXmlApplicationContext(files);

如果配置文件存在多个的情况下,推荐的加载配置文件的方式有以下几个:
2、指定总的配置文件使用import标签去包含子的配置文件,然后只加载总的配置文件即可

<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>    

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

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

注意:自动装配功能和手动装配要是同时使用,那么自动装配就不起作用。

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);
发布了25 篇原创文章 · 获赞 0 · 访问量 339

猜你喜欢

转载自blog.csdn.net/weixin_45808666/article/details/103833434
今日推荐