Spring--四种属性注入方式和复杂类型注入(数组、List、Map、prperties)详解

第一种:set方法注入

首先创建两个实体类 Car 和 User:

package pers.zhang.bean;

public class Car {
    private String  name;
    private String color;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    @Override
    public String toString() {
        return "Car [name=" + name + ", color=" + color + "]";
    }
}
package pers.zhang.bean;

public class User {
    
    private String name;
    private Integer age;
    private Car car;
    
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
    }
}

在applicationContext.xml中进行配置:

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

    <!-- set方式注入: -->
    <bean  name="user" class="pers.zhang.bean.User" >
        <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
        <property name="name" value="tom" ></property>
        <property name="age"  value="18" ></property>
        <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
        <property name="car"  ref="car" ></property>
    </bean>
    
    <!-- 将car对象配置到容器中 -->
    <bean name="car" class="pers.zhang.bean.Car" >
        <property name="name" value="保时捷" ></property>
        <property name="color" value="红色" ></property>
    </bean>
</beans>

创建测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.User;

public class Demo {
    @Test
    public void fun1(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"user对象
        User u = (User) ac.getBean("user");
        //3 打印user对象
        System.out.println(u);
    }
}

运行JUnit测试输出:

User [name=tom, age=18, car=Car [name=保时捷, color=红色]]

第二种方式:构造函数注入

首先,为User类添加3个构造函数:

package pers.zhang.bean;

public class User {
    
    private String name;
    private Integer age;
    private Car car;
    
    public User(String name, Car car) {
        System.out.println("User(String name, Car car)!!");
        this.name = name;
        this.car = car;
    }
    
    public User(Car car,String name) {
        System.out.println("User(Car car,String name)!!");
        this.name = name;
        this.car = car;
    }
    
    public User(Integer name, Car car) {
        System.out.println("User(Integer name, Car car)!!");
        this.name = name+"";
        this.car = car;
    }
    
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
    }
}

applicationContext.xml配置:
index:用于确定参数的位置
type:用于确定参数的类型
这两个属性可以完全确定一个构造函数。

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

    <!-- 将car对象配置到容器中 -->
    <bean name="car" class="pers.zhang.bean.Car" >
        <property name="name" value="保时捷" ></property>
        <property name="color" value="红色" ></property>
    </bean>

    <!-- 构造函数注入 -->
   <bean name="user2" class="pers.zhang.bean.User" >
    <!-- name属性: 构造函数的参数名
        index属性: 构造函数的参数索引
        type属性: 构造函数的参数类型  -->
      <constructor-arg name="name" value="24" index="0" type="java.lang.Integer"   ></constructor-arg>
      <constructor-arg name="car" ref="car" index="1" ></constructor-arg>
  </bean> 
</beans>

测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.User;

public class Demo {
    @Test
    public void fun2(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"user对象
        User u = (User) ac.getBean("user2");
        //3 打印user对象
        System.out.println(u);
        
    }
}

运行JUnit测试输出:

User(Integer name, Car car)!!
User [name=24, age=null, car=Car [name=保时捷, color=红色]]
第三种方式:P名称空间注入(Spring2.x版本后提供的方式)

其本质还是调空参构造,使用set方法注入。
所以我们为User添加一个显式的空参构造:

package pers.zhang.bean;

public class User {
    
    private String name;
    private Integer age;
    private Car car;
    
    public User() {
        super();
    }

    public User(String name, Car car) {
        System.out.println("User(String name, Car car)!!");
        this.name = name;
        this.car = car;
    }
    
    public User(Car car,String name) {
        System.out.println("User(Car car,String name)!!");
        this.name = name;
        this.car = car;
    }
    
    public User(Integer name, Car car) {
        System.out.println("User(Integer name, Car car)!!");
        this.name = name+"";
        this.car = car;
    }
    
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
    }
}

一定记得引入p名称空间!

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

applicationContext.xml配置:

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

    <!-- 将car对象配置到容器中 -->
    <bean name="car" class="pers.zhang.bean.Car" >
        <property name="name" value="保时捷" ></property>
        <property name="color" value="红色" ></property>
    </bean>

<!-- p名称空间注入, 走set方法
    1.导入P名称空间  xmlns:p="http://www.springframework.org/schema/p"
    2.使用p:属性完成注入
        |-值类型: p:属性名="值"
        |-对象类型: p:属性名-ref="bean名称"
 -->
    <bean  name="user3" class="pers.zhang.bean.User" p:name="Jack" p:age="20" p:car-ref="car"  ></bean>
</beans>

测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.User;

public class Demo {
    @Test
    public void fun3(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"user对象
        User u = (User) ac.getBean("user3");
        //3 打印user对象
        System.out.println(u);
        
    }
}

运行JUnit测试输出:

User [name=Jack, age=20, car=Car [name=保时捷, color=红色]]

第四种方式:SpEL注入(Spring Expression Language):

如果存在此种需求:取其他对象的属性值来创建新的对象,就可以使用SpEL。
SpEL类似于EL表达式,格式为 #{ }。
需要注意的是,SpEL不支持引用类型注入。

applicationContext.xml配置:

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

    <!-- set方式注入: -->
    <bean  name="user" class="pers.zhang.bean.User" >
        <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
        <property name="name" value="tom" ></property>
        <property name="age"  value="18" ></property>
        <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
        <property name="car"  ref="car" ></property>
    </bean>
    
    <!-- 将car对象配置到容器中 -->
    <bean name="car" class="pers.zhang.bean.Car" >
        <property name="name" value="保时捷" ></property>
        <property name="color" value="红色" ></property>
    </bean>

<!-- 
    spel注入: spring Expression Language sping表达式语言
 -->
    <bean  name="user4" class="pers.zhang.bean.User" >
        <property name="name" value="#{user.name}" ></property>
        <property name="age" value="#{user.age}" ></property>
        <property name="car" ref="car" ></property>
    </bean>

</beans>

测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.User;

public class Demo {
    @Test
    public void fun4(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"user对象
        User u = (User) ac.getBean("user4");
        //3 打印user对象
        System.out.println(u);
        
    }
}

运行JUnit测试输出:

User [name=tom, age=18, car=Car [name=保时捷, color=红色]]

复杂类型注入(数组、List、Map、prperties)

创建一个CollectionBean类:

package pers.zhang.bean;

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

public class CollectionBean {
    private Object[] arr;//数组类型注入
    private List list;//list/set 类型注入
    private Map map;//map类型注入
    private Properties prop;//properties类型注入
    
    public Object[] getArr() {
        return arr;
    }
    public void setArr(Object[] arr) {
        this.arr = arr;
    }
    public List getList() {
        return list;
    }
    public void setList(List list) {
        this.list = list;
    }
    public Map getMap() {
        return map;
    }
    public void setMap(Map map) {
        this.map = map;
    }
    public Properties getProp() {
        return prop;
    }
    public void setProp(Properties prop) {
        this.prop = prop;
    }
    @Override
    public String toString() {
        return "CollectionBean [arr=" + Arrays.toString(arr) + ", list=" + list + ", map=" + map + ", prop=" + prop
                + "]";
    }
}
  • 数组注入:
  1. 如果只向数组中注入一个值(对象),可以直接使用 value | ref 即可。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">


    <!-- 数组类型注入 -->
    <bean name="cb" class="pers.zhang.CollectionBean" >
        <!-- 如果数组中只准备注入一个值(对象),直接使用value|ref即可 -->
        <property name="arr" value="tom" ></property>
    </bean>

</beans>
  1. 如果向数组中注入多个值(对象):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">

    <!-- set方式注入: -->
    <bean  name="user" class="pers.zhang.bean.User" >
        <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
        <property name="name" value="tom" ></property>
        <property name="age"  value="18" ></property>
        <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
        <property name="car"  ref="car" ></property>
    </bean>

    <bean name="car" class="pers.zhang.bean.Car" >
        <property name="name" value="保时捷" ></property>
        <property name="color" value="红色" ></property>
    </bean>

    <!-- 复杂类型注入 -->
    <bean name="cb" class="pers.zhang.CollectionBean" >
        <!-- 数组类型注入 -->
        <property name="arr">
            <!-- 元素顺序与注入顺序一致 -->
            <array>
                <value>tom</value>
                <value>jerry</value>
                <ref bean="user" />
            </array>
        </property>
    </bean>
</beans>

测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.CollectionBean;

public class Demo {
    @Test
    public void fun5(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"cb对象
        CollectionBean cb = (CollectionBean) ac.getBean("cb");
        //3 打印cb对象
        System.out.println(cb);
        
    }
}

运行JUnit测试输出:

CollectionBean [arr=[tom, jerry, User [name=tom, age=18, car=Car [name=保时捷, color=红色]]], 
                list=null, 
                map=null,
                prop=null]
  • List注入
    List与数组相似,如果只注入一个值(对象)使用value | ref 即可。此处不再举例。
    注入多个值(对象)配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">


    <!-- set方式注入: -->
    <bean  name="user" class="pers.zhang.bean.User" >
        <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
        <property name="name" value="tom" ></property>
        <property name="age"  value="18" ></property>
        <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
        <property name="car"  ref="car" ></property>
    </bean>

    <bean name="car" class="pers.zhang.bean.Car" >
        <property name="name" value="保时捷" ></property>
        <property name="color" value="红色" ></property>
    </bean>


  <!-- 复杂类型注入 -->
    <bean name="cb" class="pers.zhang.CollectionBean" >
        <!-- 数组类型注入 -->
        <property name="list"  >
            <list>
                <value>jack</value>
                <value>rose</value>
                <ref bean="user" />
            </list>
        </property>
    </bean>

</beans>

测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.CollectionBean;

public class Demo {
    @Test
    public void fun5(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"cb对象
        CollectionBean cb = (CollectionBean) ac.getBean("cb");
        //3 打印cb对象
        System.out.println(cb);
        
    }
}

运行JUnit测试输出:

CollectionBean [arr=null, 
                list=[jack, rose, User [name=tom, age=18, car=Car [name=保时捷, color=红色]]], 
                map=null, 
                prop=null]
  • Map注入:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">


    <!-- set方式注入: -->
    <bean  name="user" class="pers.zhang.bean.User" >
        <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
        <property name="name" value="tom" ></property>
        <property name="age"  value="18" ></property>
        <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
        <property name="car"  ref="car" ></property>
    </bean>

      <bean  name="user2" class="pers.zhang.bean.User" >
        <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
        <property name="name" value="Jerry" ></property>
        <property name="age"  value="10" ></property>
        <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
        <property name="car"  ref="car" ></property>
    </bean>

    <bean name="car" class="pers.zhang.bean.Car" >
        <property name="name" value="保时捷" ></property>
        <property name="color" value="红色" ></property>
    </bean>


  <!-- 复杂类型注入 -->
    <bean name="cb" class="pers.zhang.CollectionBean" >
       <!-- map类型注入 -->
        <property name="map"  >
            <map>
                <!-- 键为字符串,值为字符串 -->
                <entry key="url" value="jdbc:mysql:///crm" ></entry>
                <!-- 键为字符串,值为对象 -->
                <entry key="user" value-ref="user"  ></entry>
                <!-- 键为对象,值为对象 -->
                <entry key-ref="user2" value-ref="user2"  ></entry>
            </map> 
        </property>
    </bean>

</beans>

测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.CollectionBean;

public class Demo {
    @Test
    public void fun5(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"cb对象
        CollectionBean cb = (CollectionBean) ac.getBean("cb");
        //3 打印cb对象
        System.out.println(cb);
        
    }
}

运行JUnit测试输出:

CollectionBean [arr=null,
               list=null, 
               map={url=jdbc:mysql:///crm, 
                   user=User [name=tom, age=18, car=Car [name=保时捷, color=红色]], 
                    User [name=Jerry, age=10, car=Car [name=保时捷, color=红色]]=User [name=Jerry, age=10, car=Car [name=保时捷, color=红色]]}, 
               prop=null]
  • Property注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">

    <!-- 复杂类型注入 -->
    <bean name="cb" class="pers.zhang.CollectionBean" >
    <!-- prperties 类型注入 -->
    <property name="prop"  >
        <props>
            <prop key="driverClass">com.jdbc.mysql.Driver</prop>
            <prop key="userName">root</prop>
            <prop key="password">1234</prop>
        </props>
    </property>

</beans>

测试方法:

package pers.zhang.test;

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

import pers.zhang.bean.CollectionBean;

public class Demo {
    @Test
    public void fun5(){
        
        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2 向容器"要"cb对象
        CollectionBean cb = (CollectionBean) ac.getBean("cb");
        //3 打印cb对象
        System.out.println(cb);
        
    }
}

运行JUnit测试输出:

CollectionBean [arr=null, 
                list=null, 
                map=null, 
                prop={driverClass=com.jdbc.mysql.Driver, password=1234, userName=root}]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 参考W3C Spring教程 Spring致力于J2EE应用的各种解决方案,而不仅仅专注于某一层解决方案。可以说S...
    王侦阅读 1,188评论 0 6
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 1,745评论 0 3
  • 1.Spring简介 Spring是J2EE开发中一个很重要的框架。它主要用来解决下面两个问题。 解决大型软件开发...
    sixleaves阅读 1,384评论 0 6
  • http://liuxing.info/2017/06/30/Spring%20AMQP%E4%B8%AD%E6%...
    sherlock_6981阅读 16,033评论 2 11
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 1,011评论 0 2