【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】文章目录

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