Spring属性注入的5种方式

今天我们来说一下Spring的属性注入

对于类成员变量来说,注入方式有三种

-构造函数注入
-属性setter方式注入
-接口注入

Spring支持前面两种,并且还支持 p名称空间注入 、spel属性注入、复杂类型注入,接下来我们来介绍一下这些注入方式


第一种:构造方法注入

● 通过构造方法注入Bean的属性值或依赖的对象,它保证了Bean实例在实例化后就可以使用
● 构造器注入在 《constructor-arg》 元素里声明的属性

代码演示:
1.编写一个javaBean

package com.zhou.ioc.demo4;

public class User {
    private String name;
    private Integer age;

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

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

2.编写applicationContext.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="user" class="com.zhou.ioc.demo4.User">
        <constructor-arg name="name" value="小明"/>
        <constructor-arg name="age" value="18"/>
    </bean>


</beans>

3.编写测试类

package com.zhou.ioc.demo4;

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

public class springDemo1 {
    @Test
    public void demo1(){
        //获得工厂
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) applicationContext.getBean("user");
        System.out.println(user);
    }
}

结果:

User{name='小明', age=18}

2.第二种方式 :Set 方法注入
使用set方法注入,在Spring配置文件种,通过 《property》设置注入的属性

案例演示:

  1. 创建一个javaBean , 里面不仅包含普通属性 还包含对象属性
package com.zhou.ioc.demo4;

public class Person {
    private String name;
    private Integer age;
    private Cat cat;

    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;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", cat=" + cat +
                '}';
    }
}

2.编写Cat 对象属性

package com.zhou.ioc.demo4;

public class Cat {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                '}';
    }
}

3.编写 applicationContext.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="person" class="com.zhou.ioc.demo4.Person">
        <property name="name" value="黄大炮"/>
        <property name="age" value="250"/>
        <property name="cat" ref="cat"/>
    </bean>

    <bean id="cat" class="com.zhou.ioc.demo4.Cat">
        <property name="name" value="胖橘"/>
    </bean>
</beans>
小提示 : ref:是用来引入其他bean对象的id或name的
  1. 编写测试类
package com.zhou.ioc.demo4;

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

public class springDemo1 {
    @Test
    public void demo(){
        //获得工厂
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
    }
}

5.结果

Person{name='黄大炮', age=250, cat=Cat{name='胖橘'}}

第3种方式:p名称空间注入

首先得引入p名称空间,这跟beans差不多 我们可以复制一下 然后对其修改就行了
xmlns:p=“http://www.springframework.org/schema/p
接着我们就可以直接去调用 直接在 标签里面填写 格式如下:
p:<属性名>=“xxx” 引入常量值
p:<属性名>-ref=“xxx” 引入其他Bean对象

案例演示:
我们就直接用上面set的案例对其就行修改一下

1.修改applicationContext.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="person" class="com.zhou.ioc.demo4.Person" p:name="大黄" p:age="18" p:cat-ref="cat"/>

    <bean id="cat" class="com.zhou.ioc.demo4.Cat" p:name="小黄" />
</beans>
这里我们添加了一个p名称空间 :xmlns:p=“http://www.springframework.org/schema/p”
然后对<bean>标签进行了修改

2.直接执行测试类得到结果

Person{name='大黄', age=18, cat=Cat{name='小黄'}}

第4种: SpEL注入

即spring表达式语言,对依赖注入进行简化
语法:#{表达式}
<bean id = " " value = “#{表达式}” 》
SpEL表达式语言:
#{ ‘hello’} :使用字符串
#{topicId}:使用另一个bean
#{topicld.add()}: 使用指定名属性, 并使用属性里的方法
#{ T (java.lang.Math).PI} : 使用静态字段或方法

代码演示:
1.创建一个Product 产品类

package com.zhou.ioc.demo4;

public class Product {
    private String name;
    private double price;
    private Category category;  //商品分类

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", category=" + category +
                '}';
    }
}

  1. 创建 Category 商品 类
package com.zhou.ioc.demo4;

public class Category {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Category{" +
                "name='" + name + '\'' +
                '}';
    }
}

3.编写 一个计算商品价格的ProductInfo 类

package com.zhou.ioc.demo4;

public class ProductInfo {
    public Double calculatePrice(){
        return Math.random() * 200;
    }
}

4.编写 applicationContext.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="product" class="com.zhou.ioc.demo4.Product">
        <property name="name" value="#{'服装'}"/>
        <!--productInfo.calculatePrice() 调用productInfo中的calculatePrice()方法-->
        <property name="price" value="#{productInfo.calculatePrice()}"/>
        <property name="category" value="#{category}"/>
    </bean>

    <bean id="productInfo" class="com.zhou.ioc.demo4.ProductInfo"/>

    <bean id="category" class="com.zhou.ioc.demo4.Category">
        <property name="name" value="#{'女装'}"/>
    </bean>

</beans>

5.结果

Product{name='服装', price=69.97578331596061, category=Category{name='女装'}}

第5种:复杂类型注入
数组类型的属性注入
List集合类型的属性注入
Set集合类型的属性注入
Map集合类型的属性注入
Properties类型的属性注入

1.编写一个demo

package com.zhou.ioc.demo5;

import java.util.*;

public class CollectionBean {
    private String[] arrs; // 数组类型

    private List<String> list;// List集合类型

    private Set<String> set; // Set集合类型

    private Map<String,Integer> map;// Map集合类型

    private Properties properties; // 属性类型

    public String[] getArrs() {
        return arrs;
    }

    public void setArrs(String[] arrs) {
        this.arrs = arrs;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Set<String> getSet() {
        return set;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public Map<String, Integer> getMap() {
        return map;
    }

    public void setMap(Map<String, Integer> map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "CollectionBean{" +
                "arrs=" + Arrays.toString(arrs) +
                ", list=" + list +
                ", set=" + set +
                ", map=" + map +
                ", properties=" + properties +
                '}';
    }
}

  1. 编写applicationContext.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="collectionBean" class="com.zhou.ioc.demo5.CollectionBean">
        <!--数组类型-->
        <property name="arrs">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
        <!--List集合的属性注入-->
        <property name="list">
            <list>
                <value>111</value>
                <value>222</value>
                <value>333</value>
            </list>
        </property>
        <!--Set集合的属性注入-->
        <property name="set">
            <set>
                <value>ddd</value>
                <value>eee</value>
                <value>fff</value>
            </set>
        </property>
        <!--Map集合的属性注入-->
        <property name="map">
            <map>
                <entry key="aaa" value="111"/>
                <entry key="bbb" value="222"/>
                <entry key="ccc" value="333"/>
            </map>
        </property>
        <!--Properties的属性注入-->
        <property name="properties">
            <props>
                <prop key="username">root</prop>
                <prop key="password">1234</prop>
            </props>
        </property>
    </bean>
</beans>

3.编写测试类

package com.zhou.ioc.demo5;

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

public class SpringDemo5 {
    @Test
    public void demo1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        CollectionBean collectionBean = (CollectionBean)applicationContext.getBean("collectionBean");

        System.out.println(collectionBean);
    }
}

4.结果

CollectionBean{arrs=[aaa, bbb, ccc], list=[111, 222, 333], set=[ddd, eee, fff], map={aaa=111, bbb=222, ccc=333}, properties={password=1234, username=root}}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值