Spring-02-IOC
阿新 • • 發佈:2020-09-19
-
一種通過描述(XML或註解)並通過第三方去生產或獲取特定物件的方式。
-
IOC理解
-
控制:誰來控制物件的建立?
傳統應用程式的物件是由程式本身建立的,使用Spring後,物件是由Spring建立的。
-
反轉:程式本身不建立物件,而變成被動地接收物件。
-
-
示例
-
新建一個maven專案,在pom.xml中匯入Spring依賴
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>匯入了spring-webmvc之後,專案中多了以下幾個依賴
-
編寫實體類
package com.hmx.pojo;
public class Hello {
}
-
傳統方式建立物件
Hello hello = new Hello();
-
使用Spring建立物件
1、在resources目錄下新建beans.xml檔案
右鍵點選resources ---》 new ---》 XML Configuration File ---》Spring Config,可以建立spring的配置檔案
2、建立物件
-
3、測試注入是否成功
/*
語法:
獲取Spring的上下文物件
ApplicationContext context = new ClassPathXmlApplicationContext("建立的Spring配置xml檔名");
取物件
Hello hello = (Hello) context.getBean("xml檔案中對應bean的id");
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
//輸出結果:com.hmx.pojo.Hello@3abbfa04,說明建立物件成功。
System.out.println(hello);
}