IoC容器创建和使用
1 容器实例化
public class HappyComponent {
//默认包含无参数构造函数
public void doWork() {
System.out.println("HappyComponent.doWork");
}
}
//方式1:实例化并且指定配置文件
//参数:String...locations 传入一个或者多个配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
//方式2:先实例化,再指定配置文件,最后刷新容器触发Bean实例化动作 [springmvc源码和contextLoadListener源码方式]
ApplicationContext iocContainer1 = new ClassPathXmlApplicationContext();
//设置配置配置文件,方法参数为可变参数,可以设置一个或者多个配置
iocContainer1.setConfigLocations("services.xml", "daos.xml");
//后配置的文件,需要调用refresh方法,触发刷新配置
iocContainer1.refresh();
2 Bean对象读取
//方式1: 根据id获取
//没有指定类型,返回为Object,需要类型转化!
HappyComponent happyComponent = (HappyComponent) iocContainer.getBean("bean的id标识");
//使用组件对象
happyComponent.doWork();
//方式2: 根据id和类型获取
HappyComponent happyComponent = iocContainer.getBean("bean的id标识", HappyComponent.class);
happyComponent.doWork();
//方式3: 根据类型获取
//根据类型获取,但是要求,同类型(当前类,或者之类,或者接口的实现类)只能有一个对象交给IoC容器管理
//配置两个或者以上出现: org.springframework.beans.factory.NoUniqueBeanDefinitionException 问题
HappyComponent happyComponent = iocContainer.getBean(HappyComponent.class);
happyComponent.doWork();
//根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,
//只要返回的是true就可以认定为和类型匹配,能够获取到。
-
容器实例化
//方式1:实例化并且指定配置文件 //参数:String...locations 传入一个或者多个配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); //方式2:先实例化,再指定配置文件,最后刷新容器触发Bean实例化动作 [springmvc源码和contextLoadListener源码方式] ApplicationContext context = new ClassPathXmlApplicationContext(); //设置配置配置文件,方法参数为可变参数,可以设置一个或者多个配置 iocContainer1.setConfigLocations("services.xml", "daos.xml"); //后配置的文件,需要调用refresh方法,触发刷新配置 iocContainer1.refresh();
-
Bean对象读取
//方式1: 根据id获取 //没有指定类型,返回为Object,需要类型转化! HappyComponent happyComponent = (HappyComponent) iocContainer.getBean("bean的id标识"); //使用组件对象 happyComponent.doWork(); //方式2: 根据类型获取 //根据类型获取,但是要求,同类型(当前类,或者之类,或者接口的实现类)只能有一个对象交给IoC容器管理 //配置两个或者以上出现: org.springframework.beans.factory.NoUniqueBeanDefinitionException 问题 HappyComponent happyComponent = iocContainer.getBean(HappyComponent.class); happyComponent.doWork(); //方式3: 根据id和类型获取 HappyComponent happyComponent = iocContainer.getBean("bean的id标识", HappyComponent.class); happyComponent.doWork(); 根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果, 只要返回的是true就可以认定为和类型匹配,能够获取到。