ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

spring-依赖注入(DI)

2022-01-16 13:31:11  阅读:49  来源: 互联网

标签:依赖 String DI spring private address 2.2 public 注入


  • 依赖注入(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 执行结果

标签:依赖,String,DI,spring,private,address,2.2,public,注入
来源: https://www.cnblogs.com/lv1024/p/15809260.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有