Ioc也稱爲依賴注入/控制反轉,Ioc容器主要負責實例化、配置和組裝Bean,開發人員不在須要寫Bean的實例化代碼,簡化代碼的同時能夠下降Bean之間的耦合度。Ioc的頂級接口是org.springframework.beans.factory.BeanFactory
,大部分狀況下咱們會用到它的子接口org.springframework.context.ApplicationContext
該接口提供了更豐富的功能。java
使用Xml配置Bean並啓動Spring容器spring
- 首先建立一個準備交給容器管理的類UserBean
public class UserBean { private Integer age; private String name; private List<String> phone; }
- 建立一個spring.xml放在resource目錄下(固然你的項目必須是一個maven項目)
<?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="user" class="com.example.demo.spring.UserBean"></bean> </beans>
- 啓動容器並從容器中獲取bean實例
public class SpringStater { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml"); UserBean userBean = context.getBean(UserBean.class); } }
這樣能夠從容器中獲取到UserBean的實例,而無需咱們寫實例化代碼。maven