Spring笔记之依赖注入

一、Spring别名配置

​ alias 设置别名 , 为bean设置别名 , 可以设置多个别名。

<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>
<!--bean就是java对象,由Spring创建和管理-->
<!--
id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符如果配置id,又配置了name,那么name是别名name可以设置多个别名,可以用逗号,分号,空格隔开如果不配置id和name,可以根据application Context.getBean(.class)获取对象;class是bean的全限定名=包名+类名
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.spring.pojo.Hello">
    <property name="name" value="Spring"/>
</bean>

二、依赖注入(DI)

  1. 依赖注入(Dependency Injection,DI)
  2. 依赖 : 指Bean对象的创建依赖于容器,Bean对象的依赖资源
  3. 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配

2.1 set方法注入(重点)

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

测试pojo类Address.java :

public class Address {
    private String address;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

Student.java:

package com.spring.pojo;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public void setBooks(String[] books) {
        this.books = books;
    }
    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }
    public void setCard(Map<String, String> card) {
        this.card = card;
    }
    public void setGames(Set<String> games) {
        this.games = games;
    }
    public void setWife(String wife) {
        this.wife = wife;
    }
    public void setInfo(Properties info) {
        this.info = info;
    }
    public void show(){
        System.out.println("name="+ name
                + ",address="+ address.getAddress()
                + ",books="
        );
        for (String book:books){
            System.out.print("<<"+book+">>\t");
        }
                System.out.println("\n爱好:"+hobbys);
        System.out.println("card:"+card);
        System.out.println("games:"+games);
        System.out.println("wife:"+wife);
        System.out.println("info:"+info);
    }
}

2.1.1 常量注入:

<bean id="student" class="com.spring.pojo.Student">
    <property name="name" value="小明"/>
</bean>
  • 测试:

    @Test
    public void test01(){
        ApplicationContext context = new 
    Class Path Xml Application Context("application Context.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
    }
    

2.1.2 Bean注入

<bean id="addr" class="com.spring.pojo.Address">
    <property name="address" value="重庆"/>
</bean>
<bean id="student" class="com.spring.pojo.Student">
    <property name="name" value="小明"/>
    //注意:这里的对象的值是一个引用,ref
    <property name="address" ref="addr"/>
</bean>

2.1.3 数组注入

<bean id="student" class="com.spring.pojo.Student">
    <property name="name" value="小明"/>
    <property name="address" ref="addr"/>
    <property name="books">
        <array>
            <value>西游记</value>
            <value>红楼梦</value>
            <value>水浒传</value>
        </array>
    </property>
</bean>

2.1.4 List注入

<property name="hobbys">
    <list>
        <value>听歌</value>
        <value>看电影</value>
        <value>爬山</value>
    </list>
</property>

2.1.5 Map注入

<property name="card">
    <map>
        <entry key="中国邮政" value="456456456465456"/>
        <entry key="建设" value="1456682255511"/>
    </map>
</property>

2.1.6 Set注入

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

2.1.7 Null注入

<property name="wife"><null/></property>

2.1.8 Properties注入

<property name="info">
    <props>
        <prop key="学号">20190604</prop>
        <prop key="性别">男</prop>
        <prop key="姓名">小明</prop>
    </props>
</property>

2.2 拓展注入实现

User.java : 【注意:这里没有有参构造器!】

public class User {
    private String name;
    private int age;
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  1. P命名空间注入 : 需要在头文件中加入约束文件。
导入约束 : xmlns:p="http://www.springframework.org/schema/p"
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.spring.pojo.User" p:name="狂神" p:age="18"/>
  1. c 命名空间注入 : 把有参构造器加上,c 就是构造器注入,需要在头文件中加入约束文件。
导入约束 : xmlns:c="http://www.springframework.org/schema/c"
<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.spring.pojo.User" c:name="狂神" c:age="18"/>
  1. 测试
@Test
public void test02(){
    ApplicationContext context = new 
Class Path Xml Application Context("application Context.xml");
    User user = (User) context.getBean("user");
    System.out.println(user);
}

三、Bean的作用域

在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲,bean就是由IoC容器初始化、装配及管理的对象 .

几种作用域中,request、session作用域仅在基于web的应用中使用(不必关心你所采用的是什么web应用框架),只能用在基于web的Spring ApplicationContext环境。

3.1 Singleton

当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。要在XML中将bean定义成singleton,可以这样配置:

<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
@Test
public void test03(){
    ApplicationContext context = new 
Class Path Xml Application Context("application Context.xml");
    User user = (User) context.getBean("user");
    User user2 = (User) context.getBean("user");
    System.out.println(user==user2);
}

3.2 Prototype

当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置:

<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>  
 或者
<bean id="account" class="com.foo.DefaultAccount" singleton="false"/> 

3.3 Request

当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>

针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request作用域的bean实例将被销毁。

3.4 Session

当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前HTTP Session内有效。与request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。

四、Bean的自动装配

  • 自动装配是使用spring满足bean依赖的一种方法
  • spring会在应用上下文中为某个bean寻找其依赖的bean。

Spring中bean有三种装配机制,分别是:

  • 在xml中显式配置;
  • 在java中显式配置;
  • 隐式的bean发现机制和自动装配。

Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;

  2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

组件扫描和自动装配组合发挥巨大威力,使的显示的配置降低到最少。但是不推荐使用自动装配xml配置 , 而是使用注解。

4.1 应用测试

  • 新建两个实体类,Cat、Dog 都有一个叫的方法

    public class Cat {
        public void shout() {
            System.out.println("miao~");
        }
    }
    
    public class Dog {
        public void shout() {
            System.out.println("wang~");
        }
    }
    
  • 新建一个用户类 User

    public class User {
        private Cat cat;
        private Dog dog;
        private String str;
    }
    
  • 编写Spring配置文件

    <?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="dog" class="com.spring.pojo.Dog"/>
        <bean id="cat" class="com.spring.pojo.Cat"/>
        <bean id="user" class="com.spring.pojo.User">
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
            <property name="str" value="zhangsan"/>
        </bean>
    </beans>
    
  • 测试

    public class MyTest {
        @Test
        public void testMethodAutowire() {
            ApplicationContext context = new 
    Class Path Xml Application Context("beans.xml");
            User user = (User) context.getBean("user");
            user.getCat().shout();
            user.getDog().shout();
        }
    }
    

4.2 byName

autowire byName (按名称自动装配)

由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。采用自动装配将避免这些错误,并且使配置简单化。

  • 修改bean配置,增加一个属性 autowire="byName"

    <bean id="user" class="com.spring.pojo.User" autowire="byName">
        <property name="str" value="zhangsan"/>
    </bean>
    
  • 再次测试,结果依旧成功输出!

  • 将 cat 的bean id修改为 catXXX

  • 再次测试, 执行时报空指针java.lang.NullPointerException。因为按byName规则找不对应set方法,真正的setCat就没执行,对象就没有初始化,所以调用时就会报空指针错误。

小结:

当一个bean节点带有 autowire byName的属性时。

  1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
  2. 去spring容器中寻找是否有此字符串名称id的对象。
  3. 如果有,就取出注入;如果没有,就报空指针异常。

4.3 byType

autowire byType (按类型自动装配)

使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

No Unique Bean Definition Exception
  • 将user的bean配置修改一下 :autowire="by Type"

  • 测试,正常输出

  • 再注册一个cat2的bean对象

    <bean id="dog" class="com.spring.pojo.Dog"/>
    <bean id="cat" class="com.spring.pojo.Cat"/>
    <bean id="cat2" class="com.spring.pojo.Cat"/>
    <bean id="user" class="com.spring.pojo.User" autowire="byType">
        <property name="str" value="zhangsan"/>
    </bean>
    
  • 测试,报错:NoUniqueBeanDefinitionException

  • 删掉cat2,将cat的bean名称改掉!测试!因为是按类型装配,所以并不会报异常,也不影响最后的结果。甚至将id属性去掉,也不影响结果,即按照类型自动装配!

五、参考资料

https://blog.kuangstudy.com/insex.php

posted on 2022-02-18 22:23  lixin05  阅读(43)  评论(0编辑  收藏  举报