Spring(六)属性依赖注入(构造方法,setter方法,p命名空间,spel表达式,集合注入)

36 篇文章 1 订阅
16 篇文章 6 订阅

属性依赖注入方式有手动装配和自动装配
一般进行的配置信息都采用手动装配,自动装配主要用在structs和spring整合。在这里只说明手动装配。

手动装配方式

手动装配方式有:

  • 构造方法方式
  • setter方法方式
  • p命名空间方式
  • spel表达式方式
  • 集合注入方式

构造方法方式

说明

构造方法方式注入即把字段放在构造方法中。然后在xml文件中为构造方法中的参数赋值。

xml配置

<bean id="" class="" >                                                                  <constructor-arg index="" type="" value="">
</constructor-arg>
</bean>

在bean标签中配置constructor-arg标签,其中index表示构造方法的第几个参数,(从0开始),type表示参数的数据类型,value表示参数的值。
constructor-arg还有另外一种方式

    <constructor-arg name="" value=""></constructor-arg>

其中构造方法中的name表示参数名,value表示参数值。一般采用第一种方式。

例子

Users类 重写了toString方法,方便下面的测试
重写了两个构造方法,注意两个构造方法参数的数据类型的区别
下面的测试我们要为uid和username赋值。即第一个构造方法。



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


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

    public Users(String username, Integer age) {
        super();
        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 "Users [uid=" + uid + ", username=" + username + ", age=" + age
                + "]";
    }

}

XML配置
其中在constructor-arg 标签中,我们为构造方法的第一个参数数据类型为java.lang.Integer,第二个参数的数据类型为java.lang.String

<?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 
                  http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="UsersId" class="com.scx.inject.test.Users" >
        <constructor-arg index="0" type="java.lang.Integer" value="5"></constructor-arg>
        <constructor-arg index="1" type="java.lang.String" value="TOM"></constructor-arg>
    </bean>
</beans>

测试:

public class Test {
    @org.junit.Test
    public void testScope() {
        String xmlPath = "com/scx/inject/test/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                xmlPath);
        Users user = applicationContext.getBean("UsersId", Users.class);
        System.out.println(user);
    }
}

运行结果:
这里写图片描述
成功为第一个构造方法赋值。

setter方法方式

说明

要使用setter方法注入 类中一定要有这个字段的setter方法 而且一定要把默认的构造方法重写。因为getBean会调用默认的构造方法。
所以相比前面的Users类 加上

public Users(){

    }

xml配置

<bean id="" class="" >
        <property name="" value=""></property>
    </bean>

使用property 标签即可 ,name表示字段名,value表示字段值

例子

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" xsi:schemaLocation=
                 "http://www.springframework.org/schema/beans 
                  http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="UsersId" class="com.scx.inject.test.Users" >
        <property name="age" value="5"></property>
        <property name="uid" value="1"></property>
        <property name="username" value="TOM"></property>
    </bean>
</beans>

测试代码不变 ,直接输出
这里写图片描述
成功为字段赋值。

p命名空间方式

说明

P命名空间方式是对上面的setter方法的简化,替换

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


若想使用p命名空间,必须添加命名空间

xmlns:p="http://www.springframework.org/schema/p"

xml配置

不要忘记添加命名空间啊

<bean id="" class="" p:字段名="字段值">

例子

在上面说了 p命名空间是对Setter方法的简化,所以只修改xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=
                 "http://www.springframework.org/schema/beans 
                  http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="UsersId" class="com.scx.inject.test.Users" p:age="10" p:uid="1" p:username="Tom">
    </bean>
</beans>

运行结果
这里写图片描述

spel表达式方式

说明

spel即Spring expression的简写 。
spel是对<property name="" value=""></property>
的简化。

xml配置

在property 标签的value里面赋值使用#{}
常用的有:

#{123}、#{‘jack’} : 数字、字符串
#{beanId} :另一个bean引用
#{beanId.propName} :操作数据
#{beanId.toString()} :执行方法
#{T(类).字段|方法} :静态方法或字段

例子

Users类,我们希望:
uid使用以前的方式注入
username使用#{beanId.propName}注入
age使用#{123}注入
address使用#{‘jack’} 注入
pi使用#{T(类).字段|方法} 注入


public class Users {
    private Integer uid;
    private String username="tom";
    private Integer age;
    private String address;
    private double pi;
    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;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public double getPi() {
        return pi;
    }
    public void setPi(double pi) {
        this.pi = pi;
    }
    @Override
    public String toString() {
        return "Users [uid=" + uid + ", username=" + username + ", age=" + age
                + ", address=" + address + ", pi=" + pi + "]";
    }   
}

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" xsi:schemaLocation=
                 "http://www.springframework.org/schema/beans 
                  http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="UsersId" class="com.scx.inject.test.Users" >
        <property name="uid" value="1"></property>
        <property name="age" value="#{10}"></property>
        <property name="username" value="#{UsersId.username?.toUpperCase()}"></property>
        <property name="pi" value="#{T(java.lang.Math).PI}"></property>
        <property name="address" value="#{'CHINA'}"></property>
    </bean>
</beans>

测试代码和前面一样。
运行结果
这里写图片描述

集合注入方式

说明

集合的注入都是给property添加子标签。

xml配置

      数组:<array>
        List:<list>
        Set:<set>
        Map:<map> ,map存放k/v 键值对,使用<entry>描述
        Properties:<props>  <prop key=""></prop>  
    普通数据:<value>
    引用数据:<ref>

例子

一个集合类CollData ,里面包含多种我们常用的集合

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

public class CollData {
    private String [] arrayData;
    private List listData;
    private Map mapData;
    private Set setData;
    private Properties propsData;
    public String[] getArrayData() {
        return arrayData;
    }
    public void setArrayData(String[] arrayData) {
        this.arrayData = arrayData;
    }
    public List getListData() {
        return listData;
    }
    public void setListData(List listData) {
        this.listData = listData;
    }
    public Map getMapData() {
        return mapData;
    }
    public void setMapData(Map mapData) {
        this.mapData = mapData;
    }
    public Set getSetData() {
        return setData;
    }
    public void setSetData(Set setData) {
        this.setData = setData;
    }
    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 + ", \nmapData=" + mapData
                + ", \nsetData=" + setData + ", \npropsData=" + propsData + "]";
    }


}

xml代码
需要特别注意的是map集合使用entry key="" value=""></entry>
键值对赋值。Properties使用

            <props>
                <prop key=""></prop>
            </props>

赋值。

<?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 
                  http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="CollDataId" class="com.scx.inject.test.CollData" >
        <!-- 为数组赋值 -->
        <property name="arrayData">
            <array>
                <value>array1</value>
                <value>array2</value>
                <value>array3</value>
            </array>
        </property>
        <!-- 为list赋值 -->
        <property name="listData">
            <list>
                <value>list1</value>
                <value>list2</value>
                <value>list3</value>
            </list>
        </property>
        <!-- 为map赋值 -->
        <property name="mapData">
            <map>
                <entry key="key1" value="value1"></entry>
                <entry key="key2" value="value2"></entry>
            </map>
        </property>
        <!-- 为set赋值 -->
        <property name="setData">
            <set>
                <value>set1</value>
                <value>set2</value>
                <value>set3</value>
            </set>
        </property>
        <!-- 为Properties赋值 -->
        <property name="propsData">
            <props>
                <prop key="一">1</prop>
                <prop key="二">2</prop>
                <prop key="三">3</prop>
            </props>
        </property>
    </bean>
</beans>

测试类

public class Test {
    @org.junit.Test
    public void testScope() {
        String xmlPath = "com/scx/inject/test/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                xmlPath);
        CollData collData = applicationContext.getBean("CollDataId", CollData.class);
        System.out.println(collData);
    }
}

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值