Spring中的IOC和DI(“最易懂得Spring学习”)

🏇 哇 咔 咔 : \textcolor{blue}{哇咔咔:} 在 上 一 篇 文 章 中 简 单 了 解 了 S p r i n g 以 及 I O C 的 理 论 推 导 \textcolor{green}{在上一篇文章中简单了解了Spring以及IOC的理论推导} SpringIOC
🏇 那 么 接 下 来 看 一 下 控 制 反 转 I O C 的 创 建 方 式 以 及 依 赖 注 入 \textcolor{pink}{那么接下来看一下控制反转IOC的创建方式以及依赖注入} IOC
🏇 中 间 我 们 也 了 解 一 下 S p r i n g 中 的 配 置 \textcolor{green}{中间我们也了解一下Spring中的配置} Spring
💥代码在gitee仓库中💥所用到的代码都可以在这里找到
🙏 博 主 也 在 学 习 阶 段 , 如 若 发 现 问 题 , 请 告 知 , 非 常 感 谢 \textcolor{Orange}{博主也在学习阶段,如若发现问题,请告知,非常感谢} 💗

🐳点击送你到《简单了解了Spring以及IOC的理论推导》

四、IOC创建对象的方式

1、使用无参构造创建对象–默认

  • <!--默认使用无参构造-->
    <bean id="user" class="com.hxl.pojo.User">
        <property name="name" value="王木木"/>
    </bean>
    

2、使用有参构造创建对象(三种方法)

  • <!--第一种,下标赋值-->
    <bean id="user" class="com.hxl.pojo.User">
        <!--这里的0代表第一个参数-->
        <constructor-arg index="0" value="王木木Sir"/>
    </bean>
    
  • <!--第二种:通过类型创建,
        不建议使用,因为如果有两个String类型就会出错-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg type="java.lang.String" value="wangmumu"/>
    </bean>
    
  • <!--第三种:直接通过参数名来设置-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg name="name" value="王木木"/>
    </bean>
    

Spring在创建bean的时候就已经给我们实例化了。也就是说只要在bean中配置了,那在运行的时候不管用不用,到会实例化(创建出一个无参构造对象)

总结:在配置文件加载的时候,容器中管理的对象已经初始化了

代码:

package com.hxl.pojo;

public class User {
    private String name;

    public User() {
        System.out.println("User的无参构造!");
    }

    public User(String name) {
        this.name = name;
    }

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

    public String getName() {
        return name;
    }

    public void show(){
        System.out.println(this.name);
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

相 同 实 体 类 三 种 方 式 不 能 同 时 存 在 哈 , 记 得 使 用 的 时 候 注 释 掉 其 他 方 式 \textcolor{Magenta}{相同实体类三种方式不能同时存在哈,记得使用的时候注释掉其他方式} 使

<?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="user" class="com.hxl.pojo.User">
    <!--这里的0代表第一个参数-->
       <constructor-arg index="0" value="王木木Sir"/>
    </bean>

    <!--第二种:通过类型创建,-->
    <!--不建议使用,因为如果有两个String类型就会出错-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg type="java.lang.String" value="wangmumu"/>
    </bean>

    <!--第三种:直接通过参数名来设置-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg name="name" value="王木木"/>
    </bean>

</beans>
import com.hxl.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //Spring容器么,就类似于婚介网站
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }
}
//下面两个方法都可以实现,一个是强转,一个是
User user = (User) context.getBean("user");
User user = context.getBean("user", User.class);

五、Spring配置

5.1 别名

<!--别名:如果添加了别名,我们也可以使用别名获取这个对象-->
<alias name="user" alias="userNew"/>

5.2 Bean的配置

<!--
    id:bean的唯一标识符,也就是对象名
    class:bean对象所对应的全限定名:包名+类型
    name:也是别名,而且name更高级,可以同时取多个别名,空格,逗号都可以识别下面有3个别名
    -->
<bean id="userT" class="com.hxl.pojo.User" name="user2 u1,u2"/>

弄了上面的话,在测试的时候类就变成了UserT

UserT user = (UserT) context.getBean("user");

5.3 import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个

假设现在项目中有多个人开发,分别负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的bean.xml合并为一个总的applicationContext.xml

在这里插入图片描述

<import resource="beans.xml"/>
public class MyTest {
    public static void main(String[] args) {
        //Spring容器么,就类似于婚介网站
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) context.getBean("user2");
        user.show();
    }
}

六、依赖注入DI

1.构造器注入

前面的hello就是构造器注入

2.Set方式注入【重点】

  • 依赖注入:Set注入!
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入
2.1【环境搭建】

1.复杂类型

package com.hxl.pojo;

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

2.真实测试对象

package com.hxl.pojo;

import java.util.*;

public class Student {
    private String name;
    //引用类型,到时候用ref赋值
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

3.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.xsd">

    <!--第一种:普通值注入:value-->
    <bean id="student" class="com.hxl.pojo.Student">
        <property name="name" value="王木木"/>
    </bean>

</beans>

4.测试类

import com.hxl.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
    }
}
2.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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.hxl.pojo.Address"/>


    <bean id="student" class="com.hxl.pojo.Student">
        <!--第一种:普通值注入:value-->
        <property name="name" value="王木木"/>
        <!--第二种,Bean注入:ref-->
        <property name="address" ref="address"/>
        <!--第三种,数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>水浒传</value>
            </array>
        </property>
        <!--第四种:List注入-->
        <property name="hobbys">
            <list>
                <value>谈恋爱</value>
                <value>敲代码</value>
            </list>
        </property>
        <!--第五种:Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="1254482515165451X"/>
                <entry key="银行卡" value="1549413214151515485"/>
            </map>
        </property>
        <!--第六种:Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>王者荣耀</value>
            </set>
        </property>
        <!--第七种:NULL-->
        <property name="wife">
            <null/>
        </property>
        <!--第八种:Properties-->
        <property name="info">
            <props>
                <prop key="学号">yj2021</prop>
                <prop key="姓名">王木木</prop>
            </props>
        </property>
    </bean>
</beans>
import com.hxl.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
        /*
        * Student{name='王木木', address=Address{address='null'}, books=[红楼梦, 水浒传], hobbys=[谈恋爱, 敲代码],
        * card={身份证=1254482515165451X, 银行卡=1549413214151515485}, games=[LOL, 王者荣耀], wife='null',
        *  info={学号=yj2021, 姓名=王木木}}

         * */
    }
}

运行之前记得在address中加入toString方法,以及在Student中的toString中加入address.toString()

3.拓展方式注入

我们可以使用p命名空间以及c命名空间

官方解释

3.1 P命名空间
  • 可以直接注入属性的值:property

在xml中插入

xmlns:p="http://www.springframework.org/schema/p"

例如:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.hxl.pojo.User" p:name="王木木" p:age="23"/>

</beans>
3.2 c命名空间注入
  • 可以通过构造器注入属性的值:construct-args

在xml中引入

xmlns:c="http://www.springframework.org/schema/c"

例如:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.hxl.pojo.User" p:name="王木木" p:age="23"/>

    <!--c命名空间注入,可以通过构造器注入属性的值:construct-args-->
    <bean id="user2" class="com.hxl.pojo.User" c:name="王木木s" c:age="23"/>

</beans>
  • 这个地方要注意,实体类中要有有参构造,否则会报错。同时要有无参构造存在,否咋p命名空间会报错
3.3 测试
@Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        User user = (User) context.getBean("user2");
        System.out.println(user.toString());
    }
}
3.4 注意

p命名空间和c命名空间不能直接使用,需要导入xml约束

4. Bean的作用域

在这里插入图片描述

4.1 单例模式singleton
<bean id="user2" class="com.hxl.pojo.User" c:name="王木木s" c:age="23" scope="singleton"/>

在这里插入图片描述

User user = (User) context.getBean("user2",User.class);
User user2 = (User) context.getBean("user2",User.class);
System.out.println(user == user2);

虽然是两个user,但是是从一个单例拿出来的,也就是创建了一个实体类

在这里插入图片描述

可以显示的定义,默认是单例

4.2 原型模式

每次从容器中get的时候,都会产生一个新对象。

<!--c命名空间注入,可以通过构造器注入属性的值:construct-args-->
<bean id="user2" class="com.hxl.pojo.User" c:name="王木木s" c:age="23" scope="prototype"/>

一旦用了这个之后再去测试上面的代码,会发现结果是false。

4.3 其余的request,session,application

这些只能在web开发中使用

评论 43
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秦 羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值