spring-依赖注入(DI)

  • 依赖注入(Dependency Injection,DI).
  • 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
  • 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .

1 构造器注入

之前的博客演示过了

2 set注入(重点)

2.1 创建实体类

2.1.1 创建Address.java

public class Address {
    private String address;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

2.1.2 创建Student.java

编写出每一种类型的属性,并添加get,set,和toString方法

public class Student {
    //普通值
    private String name;
    //引用类型
    private Address address;
    //数组
    private String[] books;
    //List
    private List<String> hobbies;
    //Map
    private Map<String,String> card;
    //Set
    private Set<String> games;
    //设置空值
    private String wife;
    //Properties
    private Properties info;
}

2.2 在配置文件中为每一种类型的属性注入值

2.2.1普通值注入

<property name="name" value="傻逼"/>

2.2.2 Bean注入

<property name="address" ref="address"/>

2.2.3 数组

<property name="books">
    <array>
        <value>水浒传</value>
        <value>三国演义</value>
        <value>西游记</value>
        <value>红楼梦</value>
    </array>
</property>

2.2.4 List

<property name="hobbies">
    <list>
        <value>打游戏</value>
        <value>看电影</value>
        <value>敲代码</value>
    </list>
</property>

2.2.5 Map

<property name="card">
    <map>
        <entry key="身份证" value="123456789987654321"/>
        <entry key="银行卡" value="1472583699638527491"/>
    </map>
</property>

2.2.6 Set

<property name="games" >
    <set>
        <value>王者荣耀</value>
        <value>地平线5</value>
        <value>闪耀暖暖</value>
    </set>
</property>

2.2.7 null

<property name="wife">
    <null/>
</property>

2.2.8 properties

<property name="info">
    <props>
        <prop key="学号">202201016</prop>
        <prop key="姓名">傻逼</prop>
        <prop key="性别">男</prop>
    </props>
</property>

2.3 测试

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);
    }
}

2.4 执行结果

spring-依赖注入(DI)

上一篇:PathEffect()详解


下一篇:Spring 学习笔记(4)依赖注入 DI