【Spring】(2)Spring 的Ioc簡單使用(創建對象)

一、IOC 本質

控制反轉IoC(Inversion of Control),是一種設計思想!

IOC是一種編程思想 ,由主動的編程(new對象)變成被動的接收(如方法setXxx(注入的對象))。

DI(依賴注入)是實現IoC思想的一種方法

狂神視頻講的Ioc本質 通俗易懂,對我非常有幫助: https://www.bilibili.com/video/BV1WE411d7Dv?p=4

下面這篇文章非常棒,講的非常詳細,推薦將Spring-IOC本質分析中的 IOC 理論 實現一下。另一篇:Spring的IOC原理

二、Spring 的簡單使用

項目結構:

在這裏插入圖片描述

pom.xml中導入spring-webmvc依賴和junit依賴。

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

com.shengjava.pojo包下創建User類。

public class User {
    private String name;

    public User() {
    }

    public String getName() {
        return name;
    }

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

在resource目錄下創建pojos.xml文件,進行如下配置。

在配置文件pojos.xml中配置的bean對象,都交給了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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- User bean(在Spring中,對象都叫做bean)
        id:對象的標識符。相當於User user = new User()中的user.
        class:全限定名(這個類的包名+類名)
     -->
    <bean id="user" class="com.shengjava.pojo.User">
        <!-- 使用bean的set方法,對bean的屬性賦值(name="xxx"中的xxx屬性一定要有set方法,否則會報錯) -->
        <property name="name" value="長生"></property>
    </bean>

</beans>

創建測試類,進行測試

public class UserTest {
    @Test
    public static void main(String[] args) {
        // create and configure beans(現在我們的對象都是Spring進行管理了,我們可以去Spring的容器ApplicationContext中獲取。context:上下文、環境的意思)
        ApplicationContext context = new ClassPathXmlApplicationContext("pojos.xml");

        // retrieve configured instance(從上下文context中獲取對象)
        User user = context.getBean("user", User.class);
        System.out.println(user);
    }
}

輸出如下:

說明我們從Spring 的ApplicationContext容器中,獲取到了一個User對象,

User{name='長生'}

參考自官方文檔:Instantiating a Container

至此,我們已經會使用Spring的配置文件進行配置,簡單的創建bean對象了,接下來要開始講DI(依賴注入)了。


相關

我的該分類的其他相關文章,請點擊:【Spring】文章目錄

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