1. 程式人生 > 其它 >Spring(3)第一個Spring程式

Spring(3)第一個Spring程式

3.HelloSpring

3.1由於我是基於Maven實現的所以就直接導包了

注 : spring 需要匯入commons-logging進行日誌記錄 . 我們利用maven , 他會自動下載對應的依賴項 .
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>

3.2 最初測試Spring

public class Hello {

    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
}

3.3編寫Spring檔案在資源裡,這裡我們命名beans.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-3.0.xsd"> <!-- 使用Spring來建立物件,在Spring這些都稱為Bean --> <bean id="hello" class="com.luo.pojo.Hello"> <property name="str" value="Spring"></property> </bean> </beans>

這時我們發現,我們在beans.xml裡出現了bean,以前我們建立物件是 型別 變數名=new 型別(); Hello hello=new Hello();

但是現在Hello物件由Spring建立了 id=變數名,class=new 的物件,property相當於給物件的屬性設定一個值!

3.4 測試

public class HelloTest {

    public static void main(String[] args) {

        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = (Hello) context.getBean("hello");

        System.out.println(hello.getStr());
    }
}

關於主要程式有以下兩個要點需要注意:

  • 第一步是我們使用框架 API ClassPathXmlApplicationContext() 來建立應用程式的上下文。這個 API 載入 beans 的配置檔案並最終基於所提供的 API,它處理建立並初始化所有的物件,即在配置檔案中提到的 beans。

  • 第二步是使用已建立的上下文的 getBean() 方法來獲得所需的 bean。這個方法使用 bean 的 ID 返回一個最終可以轉換為實際物件的通用物件。一旦有了物件,你就可以使用這個物件呼叫任何類的方法。

3.5 思考

  • Hello 物件是誰建立的 ?  
    • hello 物件是由Spring建立的
  • Hello 物件的屬性是怎麼設定的 ?
    •  hello 物件的屬性是由Spring容器設定的

這個過程就叫控制反轉 :

  • 控制 : 誰來控制物件的建立 , 傳統應用程式的物件是由程式本身控制建立的 , 使用Spring後 , 物件是由Spring來建立的
  • 反轉 : 程式本身不建立物件 , 而變成被動的接收物件 .

依賴注入 : 就是利用set方法來進行注入的.

IOC是一種程式設計思想,由主動的程式設計變成被動的接收

可以通過newClassPathXmlApplicationContext去瀏覽一下底層原始碼 .

 

 

從現在開始不用去建立物件,直接從spring檔案裡改變程式碼,獲得自己想要的結果。 IOC:物件由Spring來建立,管理,裝配!