Spring基础知识学习总结(二)

一.  (ioc)Bean的依赖注入方式

a. 基于xml文件标签的装配Bean

Spring 基于 XML 的装配通常有两种实现方式,一是设值注入,二是构造注入。 在 Spring 实例化 Bean 的过程中,首先会调用默认的构造方法实例化 Bean 对象,然后通过 Java 的反射机制调用 setXxx() 方法进行属性的注入。因此,设值注入要求一个 Bean 的对应类必须满足两个要求:一是提供一个无参构造方法;二是为需要注入的属性提供对应的 setter 方法。

使用设值注入时,在配置文件 applicationContext.xml 中需要使用 bean 元素的子元素 property 为每个属性注入值。(get set注入)

使用构造注入时,在配置文件中,需要使用 constructor-arg 标签定义构造方法的参数,可以使用其 value 属性设置该参数的值。(构造方法注入)

1> 基于 XML 的 Bean 装配实例(普通数据类型)
1. 在entity包下创建一个实体类Student

创建无参有参构造方法,get set方法,toSring方法

package com.hhh.entity;

/**
 * @author Jie.
 * @description: TODO
 * @date 2024/8/6
 * @version: 1.0
 */
public class Student {

    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
 2. 创建 Spring 配置文件(applicationContext.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" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    <!-- 使用设值注入方式装配 Student 实例 -->
    <bean id="student1" class="com.hhh.entity.Student">
        <property name="name" value="张三" />
        <property name="age" value="25" />
    </bean>

    <!-- 使用构造方法装配 Student 实例 -->
    <bean id="student2" class="com.hhh.entity.Student">
        <constructor-arg index="0" value="李四" />
        <constructor-arg index="1" value="24" />
    </bean>
</beans>

上述代码中,首先使用了设值注入方式装配 Student 类的实例,其中 property 子元素用于调用 Bean 实例中的 setXxx() 方法完成属性赋值。然后使用了构造方式装配了 Student 类的实例,其中 constructor-arg 元素用于定义构造方法的参数,其属性 index 表示其索引(从 0 开始),value 属性用于设置注入的值

3. 创建ApplicationContextTest测试注入结果
public class ApplicationContextTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 设值方式输出结果
        System.out.println("设值方式输出结果");
        System.out.println(applicationContext.getBean("student1"));
        // 构造方式输出结果
        System.out.println("构造方式输出结果");
        System.out.println(applicationContext.getBean("student2"));

    }
}

ApplicationContext:BeanFactory的子接口,加载配置文件的时候就会创建对象

2> 基于 XML 的 Bean 装配实例(数组集合数据类型的注入)

1.  在entity包下创建一个实体类CollectionBean
package com.hhh.entity;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class CollectionBean {
    public String[] strs;
    private List<String> list;
    private Map<String,String> map; //key,value形式

    public String[] getStrs() {
        return strs;
    }

    public void setStrs(String[] strs) {
        this.strs = strs;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return "CollectionBean{" +
                "strs=" + Arrays.toString(strs) +
                ", list=" + list +
                ", map=" + map +
                '}';
    }
}
2. 创建 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" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    <!-- 对数组集合数据类型的注入 -->
    <bean id="collection" class="com.hhh.entity.CollectionBean">
        <property name="strs">
            <array>
                <value>A</value>
                <value>B</value>
                <value>C</value>
                <value>D</value>
            </array>
        </property>

        <property name="list">
            <list>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </list>
        </property>

        <property name="map">
            <map>
                <entry key="aaa" value="111"></entry>
                <entry key="sss" value="222"></entry>
                <entry key="ddd" value="333"></entry>
            </map>
        </property>
    </bean>
</beans>
 3. 创建CollectionTest测试类
package com.hhh;

import com.hhh.entity.CollectionBean;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CollectionTest {
    @Test
    public void run(){
//      ApplicationContext:BeanFactory的子接口,加载配置文件的时候就会创建对象
        ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
        CollectionBean collection= (CollectionBean) ac.getBean("collection");
        System.out.println(collection.toString());
    }

    @Test
    public void run2(){
        //创建工厂对象
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        //创建读取器(xml)
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        //读取器配置文件给工厂
        reader.loadBeanDefinitions("beans.xml");
        //获取bean实例对象
        CollectionBean collection= (CollectionBean) beanFactory.getBean("collection");
        System.out.println(collection.toString());
    }

}

3> 总结 

​ 依赖注入(Dependency Injection):它是 Spring 框架核心 IOC 的具体实现。

​ 在编写程序时,通过控制反转,把对象的创建交给了 Spring,但是代码中不可能出现没有依赖的情况。

​ IOC 解耦只是降低他们的依赖关系,但不会消除。例如:业务层仍会调用持久层的方法。

​ 那这种业务层和持久层的依赖关系,在使用 Spring 之后,就让 Spring 来维护了。

​ 简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

晚睡早起₍˄·͈༝·͈˄*₎◞ ̑̑

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

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

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

打赏作者

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

抵扣说明:

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

余额充值