Spring依赖注入

1、概念

依赖注入(Dependency Injection,DI)

  • 一般指Set注入!

  • 依赖:指Bean对象的创建依赖于容器。Bean对象的依赖资源。

  • 注入:指Bean对象所依赖的资源即属性,由容器来设置和装配。

2、构造器注入

在IOC创建对象时已经提过了

详情请见:https://www.cnblogs.com/paidaxing0623/p/14293610.html

3、Set方式注入【重点】

要求被注入的属性 , 必须有set方法,set方法的方法名由set + 属性首字母大写,如果属性是boolean类型,没有set方法,是 is。

我们可以查看官方文档:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-dependencies

3.1、环境搭建

  1. 编写复杂的实体类

    public class Address {
        private String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    }
    
    public class Student {
        private String name;
        private Address address;
        private String[] books;
        private List<String> hobby;
        private Map<String,String> card;
        private Set<String> games;
        private Properties info;
        private String wife;
        // get、set
        // toString
    }
    
  2. 编写测试类

    @Test
    public void test01() throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student);
    }
    

3.2、基本类型注入

基本数据类型:使用value属性注入,也可以使用子标签

<!-- 第一种方式:使用value属性 -->
<bean id="student" class="com.jh.domain.Student">
	<property name="name" value="天下御免"/>
</bean>
<!-- 第二种方式:使用<value>子标签 -->
<property name="name">
    <value>天下御免</value>
</property>

3.3、Bean注入

引用数据类型:使用ref属性注入,也可以使用子标签

<!-- 第一种方式:使用ref属性 -->
<bean id="address" class="com.jh.domain.Address">
    <property name="address" value="武新花园"/>
</bean>
<!-- 第二种方式:使用ref子标签 -->
<bean id="student" class="com.jh.domain.Student">
	<property name="address" ref="address"/>
</bean>

3.4、数组注入

数组注入:使用子标签注入

<property name="books">
    <array>
        <value>红楼梦</value>
        <value>西游记</value>
        <value>水浒传</value>
        <value>三国演义</value>
    </array>
</property>

3.5、List注入

List注入:使用子标签注入

<property name="hobby">
    <list>
        <value>听歌</value>
        <value>敲代码</value>
        <value>打游戏</value>
        <value>看电影</value>
    </list>
</property>

3.6、Map注入

Map注入:使用子标签注入键值对

<property name="card">
    <map>
        <entry key="身份证" value="123456123456781234"/>
        <entry key="银行卡" value="123141321342323231"/>
    </map>
</property>

3.7、Set注入

Set注入:使用子标签注入键值对

<property name="games">
    <set>
        <value>LOL</value>
        <value>COC</value>
        <value>BOB</value>
    </set>
</property>

3.8、Null注入

Null注入:设置空值使用标签;设置空字符串value属性设置""

<!-- 设置值为空字符串 -->
<property name="wife" value=""></property>
<!-- 设置值为null -->
<property name="wife">
    <null/>
</property>

3.9、Properties注入

props注入:使用 标签, 子标签

<!-- 注意:map使用属性设置值,prop使用key属性设置key,标签内设置值 -->
<property name="info">
    <props>
        <prop key="driver">com.mysql.jdbc.driver</prop>
        <prop key="url">jdbc:mysql://localhost:3306/db</prop>
        <prop key="username">root</prop>
        <prop key="password">123456</prop>
    </props>
</property>

测试结果:

Student{
    name='天下御免', 
    address=Address{address='武新花园'},
    books=[红楼梦, 西游记, 水浒传, 三国演义], 
	hobby=[听歌, 敲代码, 打游戏, 看电影], 
	card={
        身份证=123456123456781234, 
        银行卡=123141321342323231
    }, 
	games=[LOL, COC, BOB], 
	info={
        password=123456, 
        url=jdbc:mysql:\\localhost:3306\db, 
        driver=com.mysql.jdbc.driver, 
        username=root
    }, 
	wife='null'
}

4、拓展方式注入

Spring 支持具有命名空间的可扩展配置格式,这些格式基于 XML 架构定义。

4.1、P命名注入

P(属性: properties )命名空间允许您使用元素的属性(而不是嵌套元素)来描述属性值协作 bean。

它就相当于set注入的一种快捷实现方式。

使用p命名空间,必须满足以下条件

  • 实体类必须有无参构造
  • 属性必须有set方法
  • 必须导入依赖

如何使用

  1. 编写一个实体类:【没有有参构造】

    public class User {
        private String name;
        private int age;
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    
  2. 在applicationContext.xml头文件中加入约束文件

    xmlns:p="http://www.springframework.org/schema/p"
    
  3. 编写bean

    <?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">
     	<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
        <bean id="user" class="com.jh.domain.User" p:name="姓名" p:age="18">
        </bean>
    </beans>
    
  4. 测试输出

    @Test
    public void test02() throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("userBean.xml");
        User user = (User) context.getBean("user");
        System.out.println(user); // User{name='姓名', age=18}
    }
    

4.2、C命名注入

在 Spring 3.1 中引入的C(构造: Constructor)命名空间允许用于配置构造函数参数而不是嵌套元素的内联属性。

它就相当于构造器注入的一种快捷方式。

使用p命名空间,必须满足以下条件:

  • 实体类必须含有有参构造器
  • 必须导入依赖

如何使用

  1. 编写实体类

    public class User {
        private String name;
        private int age;
    
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
  2. 加入c命名约束

    xmlns:c="http://www.springframework.org/schema/c"
    
  3. 编写bean

    <?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:c="http://www.springframework.org/schema/c"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="user" class="com.jh.domain.User" c:name="姓名" c:age="18"/>
    </beans>
    
  4. 测试输出

    @Test
    public void test02() throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("userBean.xml");
        User user = (User) context.getBean("user");
        System.out.println(user); // User{name='姓名', age=18}
    }
    

5、总结

  • 依赖注入是Spring非常重要的功能

  • 有Set注入和构造器注入两种方式

  • 我们可以通过配置文件进行各种数据类型的注入

    <list/> <set/> <map/> <props/> Collection List Set Map Properties等等

  • Spring也支持其他拓展方式进行依赖注入

  • 分别是p命名空间和c命名空间

  • 使用时必须导入依赖

    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:p="http://www.springframework.org/schema/p"
    
  • 它们也就相当于set和构造器注入的另一种实现方式

posted @ 2021-01-22 11:09  天下御免  阅读(85)  评论(0编辑  收藏  举报