Spring中IOC容器中獲取組件Bean
實體類
//接口
public interface TestDemo {public void doSomething();
}
// 實現類
public class HappyComponent implements TestDemo {public void doSomething() {System.out.println("HappyComponent is doing something...");}
}
創建Bean配置文件
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"><!-- 組件信息做ioc配置 ->applicationContext讀取->實例化對象--><bean id="happyComponent" class="com.atguigu.ioc_03.HappyComponent"/>
</beans>
IOC容器中獲取組件Bean
/*** 在IOC容器中獲取組件Bean*/@Testpublic void getBeanFormIocTest() {
// 1.創建IOC容器ClassPathXmlApplicationContext applicationContext1 = new ClassPathXmlApplicationContext();applicationContext1.setConfigLocations("spring-03.xml"); // 外部配置文件設置applicationContext1.refresh(); // 刷新容器 IOC、DI的動作
// 2.讀取IOC容器的組件
// 方式一:直接根據BeanId獲取 獲取的是一個Object對象 需要強制轉換[不推薦]HappyComponent happyComponent = (HappyComponent)applicationContext1.getBean("happyComponent");
// 方式二:根據BeanId和類型獲取 獲取的是一個指定類型的對象[推薦]HappyComponent happyComponent1 = applicationContext1.getBean("happyComponent", HappyComponent.class);
// 方式三:根據類型獲取 獲取的是一個指定類型的對象
// TODO 根據bean的類型獲取,同一個類型,在ioc容器中只能有一個bean!!!(如果ioc容器存在多個同類型的bean,會出現NoUniqueBeanDefinitionException[不唯一]異常)HappyComponent happyComponent2 = applicationContext1.getBean(HappyComponent.class);
// 3.使用組件happyComponent.doSomething();happyComponent1.doSomething();happyComponent2.doSomething();System.out.println(happyComponent == happyComponent1); // trueSystem.out.println(happyComponent == happyComponent2); // true
// 4.IOC的bean配置一定是實現類,但是可以根據接口類型獲取值
// getBean(,類型) 其中的類型判斷采用 instanceof ioc容器的類型 == true (接口與實現類之間是true的關系)
// 在實際業界使用這種方式,可以將部分邏輯抽離出來,封裝工具,只留接口作為對外暴露的api,繼承自該接口的直接實現類可以直接使用TestDemo testDemo = applicationContext1.getBean("happyComponent", TestDemo.class);TestDemo testDemo1 = applicationContext1.getBean(TestDemo.class); // 這樣更簡潔但是要注意 bean中同一類型只能有一個!!!testDemo.doSomething(); // HappyComponent is doing something...}