【Spring框架】Spring入门(四)——五种属性注入方式(详细代码)

导读:本篇文章讲解 【Spring框架】Spring入门(四)——五种属性注入方式(详细代码),文章出自:https://blog.csdn.net/weixin_43316702/article/details/104997044希望对大家有帮助,欢迎收藏,转发!站点地址:www.javazhiyin.com.com

>>强大,10k+点赞的 SpringBoot 后台管理系统竟然出了详细教程!

1.属性注入–构造方法
构造方法的方式注入就是通过构造方法内的参数的属性类型个数判断传入的值是属于哪个属性的。
User类:

public class User {
    private Integer uid;
    private String username;
    private Integer age;

    public User(Integer uid, String username) {
        this.uid = uid;
        this.username = username;
    }

    public User(String username, Integer age) {
        this.username = username;
        this.age = age;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", age=" + age +
                '}';
    }

bean.xml:

<!-- 构造方法注入
             *<constructor-arg></constructor-arg> 用于配置构造方法一个参数argument
                name :参数的名称
                value:设置普通数据
                ref  :引用数据,一般是另一个bean id值
                index:参数的索引号,从0开始。如果只有索引,匹配到了多个构造方法时,默认使用第一个
                type :
                例如1:使用名称name
                        <constructor-arg name="username" value="Jack"></constructor-arg>
                        <constructor-arg name="age" value="18"></constructor-arg>
                例如2:类型type 和 索引index(会根据构造方法位置,索引和类型匹配)
                        <constructor-arg index="0" type="java.lang.String" value="Jack"></constructor-arg>
                        <constructor-arg index="1" type="java.lang.Integer" value="18"></constructor-arg>
        -->
        
        <bean id="userId" class="com.spring.f_xml.a_constructor.User">
                <constructor-arg index="0" type="java.lang.String" value="Jack"></constructor-arg>
                <constructor-arg index="1" type="java.lang.Integer" value="18"></constructor-arg>
        </bean>

测试类:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestCons {
    @Test
    public void demo02() {
        //spring工厂
        String xmlPath = "com/spring/f_xml/a_constructor/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        User user = applicationContext.getBean("userId", User.class);
        System.out.println(user);
    }
}

//运行结果是:
//User{uid=null, username='Jack', age=18}

2.属性注入–setter方法
setter方法的方式注入就是指定需要传值的属性和需要传入的值,然后通过setter方法创建数据,注意这些操作都是交给spring容器完成的。
Person类:

public class Person {
    private String pname;
    private Integer age;
    private Address homeAddr;//家庭地址
    private Address companyAddr;//公司地址


    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public Integer getAge() {
        return age;
    }

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

    public Address getHomeAddr() {
        return homeAddr;
    }

    public void setHomeAddr(Address homeAddr) {
        this.homeAddr = homeAddr;
    }

    public Address getCompanyAddr() {
        return companyAddr;
    }

    public void setCompanyAddr(Address companyAddr) {
        this.companyAddr = companyAddr;
    }

    @Override
    public String toString() {
        return "Person{" +
                "pname='" + pname + '\'' +
                ", age=" + age +
                ", homeAddr=" + homeAddr +
                ", companyAddr=" + companyAddr +
                '}';
    }
}

Address类:

public class Address {
    private String addr;//地址信息
    private String tel;//电话

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    @Override
    public String toString() {
        return "Address{" +
                "addr='" + addr + '\'' +
                ", tel='" + tel + '\'' +
                '}';
    }
}

bean.xml:

<!--setter方法注入
           *普通数据
            <property name="age" value="18"></property>
            等效于
            <property name="age" >
                <value>18</value>
            </property>
           *引用数据
            <property name="homeAddr" ref="另一个bean"></property>
        -->
        <bean id="personId" class="com.spring.f_xml.b_setter.Person">
                <property name="pname" value="java" ></property>
                <property name="age" value="18"></property>
                <property name="homeAddr" ref="homeAddrId"></property>
                <property name="companyAddr">
                        <ref bean="companyAddrId"/>
                </property><!--此处是两种写法-->
        </bean>

        <bean id="homeAddrId" class="com.spring.f_xml.b_setter.Address">
                <property name="addr" value="弗兰"></property>
                <property name="tel" value="911"></property>
        </bean>
        <bean id="companyAddrId" class="com.spring.f_xml.b_setter.Address">
                <property name="addr" value="奥尔良"></property>
                <property name="tel" value="912"></property>
        </bean>

测试类:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSetter {
    @Test
    public void demo01() {
        //从spring容器获得
        //1.获取容器
        String xmlPath = "com/spring/f_xml/b_setter/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        //2.获得内容,不需要自己new一个对象
        Person person = (Person) applicationContext.getBean("personId");
        System.out.println(person);
    }
}

//运行结果:
//Person{pname='java', age=18, homeAddr=Address{addr='弗兰', tel='911'}, companyAddr=Address{addr='奥尔良', tel='912'}}

3.属性注入–p命名空间
Person类、Address类此处省略(与setter方法的一样)
bean.xml:(在Spring配置的bean节点中添加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">
<!--文件头要记得哟-->
        <bean id="personId" class="com.spring.f_xml.c_p.Person"
              p:pname="tommy" p:age="20"
              p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId">
        </bean>

        <bean id="homeAddrId" class="com.spring.f_xml.c_p.Address"
                p:addr="中国" p:tel="135">
        </bean>
        <bean id="companyAddrId" class="com.spring.f_xml.c_p.Address"
                p:addr="澳大利亚" p:tel="756">
        </bean>
</beans>

测试类:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestP {
    @Test
    public void demo01() {
        //从spring容器获得
        //1.获取容器
        String xmlPath = "com/spring/f_xml/c_p/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        //2.获得内容,不需要自己new一个对象
        Person person = (Person) applicationContext.getBean("personId");
        System.out.println(person);
    }
}

//运行结果:
//Person{pname='tommy', age=20, homeAddr=Address{addr='中国', tel='135'}, companyAddr=Address{addr='澳大利亚', tel='756'}}

4.属性注入–SpEL
Customer类:

public class Customer {
    private String cname = "jack";
    private Double pi;//=Math.PI

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public Double getPi() {
        return pi;
    }

    public void setPi(Double pi) {
        this.pi = pi;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "cname='" + cname + '\'' +
                ", pi=" + pi +
                '}';
    }
}

bean.xml:

		<!--
                <property name="cname" value="#{'jack'}"></property>
                        通过另一个bean,获得属性,调用的方法
                <property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
                        ?,如果对象不为null,则执行方法
        -->
        <bean id="customerId" class="com.spring.f_xml.d_spei.Customer">
                <property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
                <property name="pi" value="#{T(java.lang.Math).PI}"></property>
        </bean>

测试类:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpEL {
    @Test
    public void demo02() {
        //spring工厂
        String xmlPath = "com/spring/f_xml/d_spei/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        Customer customer = applicationContext.getBean("customerId", Customer.class);
        System.out.println(customer);
    }
}

//运行结果:
//Customer{cname='JACK', pi=3.141592653589793}

5.属性注入–集合注入
CollData类:

import java.util.*;

public class CollData {
    private String[] arrayData;
    private List<String> listData;
    private Set<String> setData;
    private Map<String,String> mapData;
    private Properties propsData;

    public String[] getArrayData() {
        return arrayData;
    }

    public void setArrayData(String[] arrayData) {
        this.arrayData = arrayData;
    }

    public List<String> getListData() {
        return listData;
    }

    public void setListData(List<String> listData) {
        this.listData = listData;
    }

    public Set<String> getSetData() {
        return setData;
    }

    public void setSetData(Set<String> setData) {
        this.setData = setData;
    }

    public Map<String, String> getMapData() {
        return mapData;
    }

    public void setMapData(Map<String, String> mapData) {
        this.mapData = mapData;
    }

    public Properties getPropsData() {
        return propsData;
    }

    public void setPropsData(Properties propsData) {
        this.propsData = propsData;
    }

    @Override
    public String toString() {
        return "CollData{" +
                "\narrayData=" + Arrays.toString(arrayData) +
                ", \nlistData=" + listData +
                ", \nsetData=" + setData +
                ", \nmapData=" + mapData +
                ", \npropsData=" + propsData +
                '}';
    }
}

bean.xml:
(数组与List集合的注入方式是一样的,map由于是以键值对的形式存储的,所以注入是有一点区别。)

<!--集合的注入都是给<property>添加字标签
                数组:<array>
                List:<list>
                Set :<set>
                Map :<map>  map存放k/v 键值对,使用<entry>描述
                Properies:<props>

            普通数据:<value>
            引用数据:<ref>
        -->
        <bean id="collDataId" class="com.spring.f_xml.e_coll.CollData">
                <property name="arrayData">
                        <array>
                                <value>数组一</value>
                                <value>数组二</value>
                                <value>数组三</value>
                                <value>数组四</value>
                        </array>
                </property>
                <property name="listData">
                        <list>
                                <value>列表一</value>
                                <value>列表二</value>
                                <value>列表三</value>
                                <value>列表四</value>
                        </list>
                </property>
                <property name="setData">
                        <set>
                                <value>set一</value>
                                <value>set二</value>
                                <value>set三</value>
                        </set>
                </property>
                <property name="mapData">
                        <map>
                                <entry key="jack" value="杰克"></entry>
                                <entry>
                                        <key><value>rose</value></key>
                                        <value>罗斯</value>
                                </entry>
                        </map>
                </property>
                <property name="propsData">
                        <props>
                              <prop key="高富帅"></prop>
                              <prop key="白富美"></prop>
                        </props>
                </property>
        </bean>

测试类:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestColl {
    @Test
    public void demo02() {
        //spring工厂
        String xmlPath = "com/spring/f_xml/e_coll/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        CollData collData = applicationContext.getBean("collDataId", CollData.class);
        System.out.println(collData);
    }
}

//运行结果:
/*
CollData{
arrayData=[数组一, 数组二, 数组三, 数组四], 
listData=[列表一, 列表二, 列表三, 列表四], 
setData=[set一, set二, set三], 
mapData={jack=杰克, rose=罗斯}, 
propsData={高富帅=嫐, 白富美=嬲}}
*/

下一节:【Spring框架】Spring入门(五)——注解