Spring學習之路——HelloSpring,IOC創建對象之方式

一、HelloSpring

學習一個新的框架當然需要讓他輸出HelloWorld咯!!!這次我們來輸出一手HelloSpring好了.
寫之前別忘了導包喲!!!

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.10.RELEASE</version>
</dependency>

這裏我們先創建一個HelloSpring類,裏面hello方法輸出HelloSpring

public class HelloSpring {
    public void hello(){
        System.out.println("HelloSpring");
    }

}

之後編寫一個Spring文件,我們叫做beans

<?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="Hello" class="HelloSpring"></bean>
</beans>

其中上方的bean就是Java對象,由Spring創建及管理!至於具體的創建過程以及如何對屬性賦值等我將會在後面記錄,這裏大家可以理解成實例化出來一個HelloSpring的實例,名字叫做Hello.
之後我們編寫測試方法.

public class Mytest {
    public static void main(String[] args) {
        //解析beans.xml文件 , 生成管理相應的Bean對象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //getBean : 參數即爲spring配置文件中bean的id .
        HelloSpring hellos = (HelloSpring) context.getBean("Hello");
        hellos.hello();
    }
}


最後當然是輸出我們想看見的結果啦!!
在這裏插入圖片描述那麼HelloSpring對象在IOC容器中到底如何創建的呢????我們趕緊來康康。

二、IOC創建對象之方式

我們把之前的HelloSpring類先添加一個無參構造康康.

public class HelloSpring {
    public HelloSpring(){
        System.out.println("這是無參構造");
    }
    public void hello(){
        System.out.println("HelloSpring");
    }

}

其他代碼不變。
在這裏插入圖片描述
我們發現在調用hello方法之前就已經調用了構造方法.
結論: 在執行getBean的時候, user已經創建好了 , 通過無參構造.
然後我們在康康有參構造的情況.我們改一改代碼.創建一個name屬性。

public class HelloSpring {
    private String name;
    public HelloSpring() {
        System.out.println("這是無參構造");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public HelloSpring(String name)
    {
        System.out.println("這是"+this.getName()+"的構造方法");
    }
    public void hello(){
        System.out.println("HelloSpring");
    }

}

然後我們要修改一下beans,我們要把參數寫入beans中.
這裏Spring提供三種方式傳參

<bean id="Hello" class="HelloSpring">
    <constructor-arg type="java.lang.String" value="髒麗麗"/>
</bean>

第一個就是通過參數的種類傳參,後面value是值.

<bean id="Hello" class="HelloSpring">
    <!-- index指構造方法 , 下標從0開始 -->
    <constructor-arg index="0" value="髒麗麗"/>
</bean>

第二個就是通過index值來傳參.

<bean id="Hello" class="HelloSpring">
       <constructor-arg name="name" value="髒麗麗"/>
</bean>

第三個是通過參數的名字來調用.
這三種都是可以正常輸出的
在這裏插入圖片描述結論:在配置文件加載的時候。其中管理的對象都已經初始化了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章