Spirng IoC/DI容器 的helloworld工程2-多个配置文件

来源:互联网 发布:移动硬盘 知乎 编辑:程序博客网 时间:2024/05/18 00:16

实际开发可以多人参与,一个模块对应一个配置文件
这里写图片描述

配置文件applicationContext.xml中

<!-- 配置公共的bean -->

配置文件applicationContext-user.xml中

<import resource="applicationContext.xml"/><bean name="user-test" class="cn.javass.spring3.hello.ImplOne"></bean>

配置文件applicationContext-dep.xml中

<bean name="dep-test" class="cn.javass.spring3.hello.ImplTwo"></bean>

1.读取多个配置文件

public class Client {    public static void main(String[] args) {        // 第一步:读配置文件,来创建ApplicationContext,相当于bean的工厂        ApplicationContext context = new ClassPathXmlApplicationContext(                new String[] { "applicationContext.xml",                        "applicationContext-user.xml",                        "applicationContext-dep.xml" });        // 第二步:获取需要操作的bean        Api api = (Api) context.getBean("dep-test");        ////////// 第三步:以下和spring就没有关系了,面向接口编程////////////        String s = api.t(21);        System.out.println("s==" + s); // 打印要有前缀    }}

1.如果多个配置文件中有name相同的bean,按照ClassPathXmlApplicationContext()装载顺序,后面的bean回覆盖前面的bean,所以bean的命名要规范,bean命名前加上模块名

2.读取一次xml,也就是执行ClassPathXmlApplicationContext()方法,并不会创建一个IoC容器的实例。
所以一次装载所有配置文件,节约资源
如下

//不创建bean容器ApplicationContext context2 = new ClassPathXmlApplicationContext(new String[] { "applicationContext-user.xml", "applicationContext-dep.xml" }); Api apis = (Api) context2.getBean("dep-test"); //创建bean容器

证明对象被创建几次,可以在构造函数中输出一句话
如下

public class ImplOne implements Api {    public ImplOne() {        // 每次创建一个对象,会执行一次        System.out.println("oneooooooooo");    }    @Override    public String t(int a) {        // TODO Auto-generated method stub        System.out.println("now in Impl One t,a==" + a);        return "hello==" + a;    }}

配置文件的内容
1.全限定类名的配置
2.行为的配置
3.参数的配置
4.关系的配置

bean的名称:按照java的变量命名,因为

<!--相当于Api api = new ImplOne();-->  <bean name="test" class="cn.javass.spring3.hello.ImplOne"></bean>

Bean的别名,和name一样用

<bean name="dep-test" class="cn.javass.spring3.hello.ImplOne"></bean><!--给上述bean设置别名cc--><alias name="dep-test" alias="cc"></alias>

容器实例化bean的技术:反射
方法1.通过构造器

<bean name="dep-test" class="cn.javass.spring3.hello.ImplOne"></bean>
0 0
原创粉丝点击