spring5 入门(二) 依赖注入,set不同类型变量注入方式详解

何为依赖注入?

  • 依赖是指通过IOC容器创建对象
  • 注入是指对象的成员变量由容器来设置和装配

注入方式

1,构造器注入 ,即通过constructor-arg这个字段进行有参构造

    <bean id="helloarg" class="com.hys.pojo.Hello" scope="singleton" >
        <constructor-arg name="str" value="kokokoko"/>
    </bean>

2.set注入 重点 不同类型的注入方式,测试类的变量包含数组,set,list,map集合,引用对象,properties,如下

public class Student {
    private String name;
    private teacher teacher;
    private String[] hobby;
    private List<String> book;
    private Set<String> games;
    private Map<String,String> cards;
    private Properties prop;

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

    public void setTeacher(com.hys.pojo.teacher teacher) {
        this.teacher = teacher;
    }

    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }

    public void setBook(List<String> book) {
        this.book = book;
    }


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

    public void setCards(Map<String, String> cards) {
        this.cards = cards;
    }

    public void setProp(Properties prop) {
        this.prop = prop;
    }

}

针对以上不同类型变量的注入方式,如下:

<?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">


    <bean id="mingqiang" class="com.hys.pojo.teacher">
        <property name="name">
            <null></null>
        </property>
        <property name="id" value="12313"/>
    </bean>

    <bean id="student" name="s1,s2,s3" class="com.hys.pojo.Student">
        <property name="name" value=""/>
        <property name="teacher" ref="mingqiang"/>
        <property name="hobby">
            <array>
                <value>游戏</value>
                <value>逻辑推理</value>
                <value>足球</value>
                <value>羽毛球</value>
            </array>
        </property>
        <property name="book">
            <list>
                <value>平凡的世界</value>
                <value>罗斯蔡德尔家族</value>
                <value>茶花女</value>
            </list>
        </property>
        <property name="games">
            <set>
                <value>英雄联盟</value>
                <value>炉石传说</value>
                <value>王者荣耀</value>
            </set>
        </property>
        <property name="cards">
            <map>
                <entry key="学生证" value="1315212015"/>
                <entry key="卡号" value="1304821"/>
            </map>
        </property>
        <property name="prop">
            <props>
                <prop key="username">123456789</prop>
                <prop key="pwd">1111</prop>
            </props>
        </property>
    </bean>

</beans>

 

spring5 入门(二) 依赖注入,set不同类型变量注入方式详解

上一篇:mac 上配置 maven


下一篇:Java EE/J2EE什么鬼?