1. 程式人生 > 實用技巧 >Spring-02-IOC

Spring-02-IOC

  • IOC(Inversion Of Control)定義

    一種通過描述(XML或註解)並通過第三方去生產或獲取特定物件的方式。

  • IOC理解

    • 控制:誰來控制物件的建立?

      傳統應用程式的物件是由程式本身建立的,使用Spring後,物件是由Spring建立的。

    • 反轉:程式本身不建立物件,而變成被動地接收物件。

  • 示例

    • 新建一個maven專案,在pom.xml中匯入Spring依賴

      <dependencies>
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.4.RELEASE</version>
      </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的配置檔案

      <?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">

      </beans>

      2、建立物件

      <?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
      https://www.springframework.org/schema/beans/spring-beans.xsd">

      <!--語法:
      <bean id="物件變數名" class="new的物件所在的位置"></bean>
      -->
      <bean id="hello" class="com.hmx.pojo.Hello"></bean>

      </beans>

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);
}