06 Spring框架 依赖注入(三)多配置文件

在Spring前几节的学习中我们都使用了一个配置文件,就像struts2中可以包含其他的配置文件,我们能不能使用多个配置文件呢(在工程比庞大,配置比较多的时候)?

Spring多配置文件分为两种:

  • 平等关系的配置文件
  • 包含子配置文件

(一)平等关系的配置文件 

  我们可以创建两个配置文件在包下 :

  

我们可以同时使用这两个配置文件在我们的应用当中,使用的方式由很多种,这里我举出比较常用的几种:

 ①

     //Spring-*.xml只要配置文件的前缀相同我们就可以这样使用
     String resource = "com/testConfig/Spring-*.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(resource);

② 

我们看看ClassPathXmlApplicationContext的构造函数,第四个构造函数提供了多个参数,这也就是说我们可以填写几个配置文件的String路径。

 @Test
    public void Test02() {
        String resource1 = "com/testConfig/Spring-base.xml";
        String resource2 = "com/testConfig/Spring-equal.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(resource1,resource2);
        Book book = (Book)ac.getBean("book");
        System.out.println(book);
    }

③ 我们观察上面的ClassPathXmlApplicationContext构造函数,我们同样可以填写一个路径字符串数组:

 @Test
    public void Test03() {
        String resource1 = "com/testConfig/Spring-base.xml";
        String resource2 = "com/testConfig/Spring-equal.xml";
        String[]resource = {resource1,resource2};
        ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
        Book book = (Book)ac.getBean("book");
        System.out.println(book);
    }

====================================================================

(二)包含子配置文件 

上面说的几种方法在地位上都是平等的,接下来我们来配置一个主配置文件的子配置文件: 

这种包含关系的配置文件和Struts2中的方式就比较像了只需要在主配置文件中加一个import标签:

同样的如果在主配置文件base中要import多个配置文件的话,我们也可以这样:

<!--引入多个配置文件-->
<import resource="Spring-*.xml">
<!--注意:总的配置文件不能和包含的子配置文件格式相同,否则会将自身包含进去,出错-->

版权声明:本文为博主原创文章,如需转载请表明出处。 https://blog.csdn.net/qq_39266910/article/details/78730032

原文地址:https://www.cnblogs.com/chengshun/p/9776707.html