A接口
package com.atguigu.Ioc_03;public interface A {void dowork();
}
HappyComponent.java
package com.atguigu.Ioc_03;public class HappyComponent implements A {// 默认包含无参的构造方法@Overridepublic void dowork() {System.out.println("我是:HappyComponent.dowork。");}
}
resouces文件夹下的 spring-03.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd"><bean id="happyComponent" class="com.atguigu.Ioc_03.HappyComponent"></bean></beans>
这个是测试类:SpringIocTest.java
package com.atguigu.test;import com.atguigu.Ioc_03.A;
import com.atguigu.Ioc_03.HappyComponent;import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;Ioc容器创建,和,读取组件的测试类
public class SpringIocTest {讲解,如何创建Ioc容器,并读取配置文件信息,如下,创建容器:选择合适的容器即可*接口BeanFactoryApplicationContext*实现类a. ClassPathXmlApplicationContext:通过读取类路径下的XML格式的配置文件,创建IOC容器对象b. FileSystemXmlApplicationContext:通过文件系统路径,读取XML格式的配置文件,创建IOC容器对象c. AnnotationConfigApplicationContext:通过读取Java配置类,创建IOC容器对象d. WebApplicationContext:专门为Web应用准备,基于Web环境创建IOC容器对象,并将对象引入存入ServletContext域中public void createIoc(){方式1:直接创建容器,并指定配置文件即可ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-03.xml");方式2:先创建Ioc容器对象,再指定配置文件,再刷新(这种方式,是源码的配置过程)ClassPathXmlApplicationContext applicationContext1 = new ClassPathXmlApplicationContext();applicationContext1.setConfigLocations("spring-03.xml"); // 外部配置文件的设置applicationContext1.refresh(); // 调用Ioc容器和DI的流程}讲解,如何在Ioc容器中获取组件Bean@Testpublic void getBeanFromIoc(){步骤1、先创建Ioc容器对象ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();applicationContext.setConfigLocations("spring-03.xml");applicationContext.refresh();步骤2、读取Ioc容器组件,有如下3个方案,方案1:直接根据BeanId获取即可,返回值类型是Object,需要强转(不推荐这种方式)HappyComponent happyComponent = (HappyComponent) applicationContext.getBean("happyComponent");方案2:根据BeanId,同时指定Bean的类型ClassHappyComponent happyComponent1 = applicationContext.getBean("happyComponent", HappyComponent.class);方案3:直接根据类型获取注意1:如果Ioc容器,存在多个同类型的bean(id不同,class相同),此时会报NoUniqueBeanDefinitionException错误注意2:Ioc的配置一定是实现类,但是可以根据接口类型获取值HappyComponent happyComponent2 = applicationContext.getBean(HappyComponent.class);A happyComponent3 = applicationContext.getBean(A.class);happyComponent3.dowork(); // 我是:HappyComponent.dowork。System.out.println("------------------------");happyComponent.dowork(); // 我是:HappyComponent.dowork。System.out.println(happyComponent == happyComponent1); // trueSystem.out.println(happyComponent1 == happyComponent2); // true}
}