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配置文件




    
        
        
    



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配置文件






    
        
        
        
    

    
        
    

小提示 : 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 配置文件





    

    

这里我们添加了一个p名称空间 :xmlns:p=“http://www.springframework.org/schema/p”
然后对标签进行了修改

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

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

第4种: SpEL注入

即spring表达式语言,对依赖注入进行简化
语法:#{表达式}
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





    
        
        
        
        
    

    

    
        
    


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 list;// List集合类型

    private Set set; // Set集合类型

    private Map map;// Map集合类型

    private Properties properties; // 属性类型

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

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

    public List getList() {
        return list;
    }

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

    public Set getSet() {
        return set;
    }

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

    public Map getMap() {
        return map;
    }

    public void setMap(Map 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



    
    
        
        
            
                aaa
                bbb
                ccc
            
        
        
        
            
                111
                222
                333
            
        
        
        
            
                ddd
                eee
                fff
            
        
        
        
            
                
                
                
            
        
        
        
            
                root
                1234
            
        
    

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

你可能感兴趣的:(Spring)