史上最全Spring教程,从零开始带你深入♂学习(二)——Spring依赖注入DI、Bean作用域、Bean的自动装配

222 阅读7分钟

Spring框架(二)——Spring依赖注入DI、Bean作用域、Bean的自动装配

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

构造器注入

构造器注入:blog.csdn.net/qq_36972826…

set注入 (重点)

要求被注入的属性 , 必须有set方法

一、创建实体类

领取资料

package com.study.pojo;

public class Address {
    private String address;
//加群1025684353一起吹水聊天
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

package com.study.pojo;

import java.util.*;

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;

    public String getName() {
        return name;
    }//加群1025684353一起吹水聊天

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

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }//加群1025684353一起吹水聊天

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    private Properties info;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address.toString() +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }//加群1025684353一起吹水聊天
}

1、常量注入

领取资料

<bean id="student" class="com.study.pojo.Student">
    <property name="name" value="小明"/>
</bean>

2、Bean注入

注意:对象是一个引用,ref

<bean id="addr" class="com.study.pojo.Address">
    <property name="address" value="广西"/>
</bean>//加群1025684353一起吹水聊天
<bean id="student" class="com.sutdy.pojo.Student">
    <property name="name" value="小明"/>
    <property name="address" ref="addr"/>
</bean>

3、数组注入

<bean id="student" class="com.study.pojo.Student">
    <property name="name" value="小明"/>
    <property name="address" ref="addr"/>
    <property name="books">
    <array>//加群1025684353一起吹水聊天
        <value>西游记</value>
        <value>红楼梦</value>
        <value>水浒传</value>
    </array>
    </property>
</bean>

4、List注入

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

领取资料

5、Map注入

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

6、set注入

<property name="games">
    <set>
        <value>LOL</value>
        <value>BOB</value>
        <value>COC</value>
    </set>
</property>
//加群1025684353一起吹水聊天

7、Null注入

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

8、Properties注入

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

领取资料

完整版

<?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">

    <!--1、常量注入-->
    <!--<bean id="student" class="com.study.pojo.Student">
        <property name="name" value="小明"/>
    </bean>-->

    <!--2、bean注入-->
    <bean id="address" class="com.study.pojo.Address">
        <property name="address" value="广西"/>
    </bean>
    <!--2、数组注入-->
    <bean id="student" class="com.study.pojo.Student">
        <property name="name" value="张三"/>
        <property name="address" ref="address"/>
        <property name="books">
            <array>//加群1025684353一起吹水聊天
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--3、List注入-->
        <property name="hobbys">
            <list>
                <value>唱</value>
                <value>跳</value>
                <value>rep</value>
                <value>篮球</value>
            </list>
        </property>
        <!--4、Map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="123"/>
                <entry key="学生证" value="456"/>
            </map>
        </property>
        <!--3、Set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--3null注入-->
        <property name="wife">
            <null/>
        </property>
        <!--3、Properties注入-->
        <property name="info">
            <props>//加群1025684353一起吹水聊天
                <prop key="学号">456</prop>
                <prop key="username">张三</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
</beans>

二、编写测试类

领取资料

import com.study.pojo.Student;
import com.study.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = context.getBean("student", Student.class);
        System.out.println(student.toString()
        );
    }

三、打印结果

image

image

image

拓展注入实现

一、编写实体类: 【注意:这里没有有参构造器!】

package com.study.pojo;

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

领取资料

二、编写spring配置文件【userbeans.xml】

1、P命名空间注入 : 需要在头文件中假如约束文件 **导入约束 : xmlns:p="www.springframework.org/schema/p"

<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.study.pojo.User" p:name="张三" p:age="18"/>

2、c 命名空间注入 : 需要在头文件中假如约束文件 **导入约束 : xmlns:c="www.springframework.org/schema/c"

<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.study.pojo.User" c:name="李四" c:age="18"/>

image

三、编写测试类

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2", User.class);
    System.out.println(user);//加群1025684353一起吹水聊天
}

测试结果:

领取资料 image

Bean的作用域

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

类别说明
singleton在Spring IOC容器中仅存在一个Bean实例(单例),Bean以单例方式存在,默认值
prototype每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean时,相当于执行new XxxBean()
request每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境
seesion同一个HTTP Session共享一个Bean,不同Session使用不同Bean,仅适用于WebAppcationContext环境

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

1、Singleton

当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例(单例),并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。

<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">

2、 Prototype

当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。

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

3、Request

当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。

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

4、Session

当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。

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

Bean的自动装配

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

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

  1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
  2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

推荐不使用自动装配xml配置 , 而使用注解。

环境搭建

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

package com.study.pojo;

public class Cat {
    public void shout(){//加群1025684353一起吹水聊天
        System.out.println("miao~");
    }
}

package com.study.pojo;

public class Dog {
    public void shout(){
        System.out.println("wang~");
    }
}

2、新建一个用户类 User

package com.study.pojo;

public class People {
    private Cat cat;
    private Dog dog;
    private String name;
}

3、 编写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.study.pojo.Dog"/>
    <bean id="cat" class="com.study.pojo.Cat"/>
    <bean id="user" class="com.study.pojo.User">
        <property name="cat" ref="cat"/>//加群1025684353一起吹水聊天
        <property name="dog" ref="dog"/>
        <property name="str" value="zhangsan"/>
    </bean>
</beans>

领取资料 4、测试

public class MyTest {
@Test
public void testMethodAutowire() {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    User user = (User) context.getBean("user");//加群1025684353一起吹水聊天
    user.getCat().shout();
    user.getDog().shout();
    }
}

5、打印结果 image

一、byName

autowire byName (按名称自动装配)

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

<bean id="user" class="com.study.pojo.User" autowire="byName">
    <property name="str" value="zhangsan"/>
</bean>

二、byType

autowire byType (按类型自动装配)

将user的bean配置修改一下 : autowire="byType"

<bean id="user" class="com.kuang.pojo.User" autowire="byType">
    <property name="str" value="qinjiang"/>
</bean>

领取资料

三、使用注解

1. 在spring配置文件中引入context文件头

xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd

2. 开启属性注解支持!

<context:annotation-config/>

image

(一)@Autowired

@Autowired是按类型自动转配的,不支持id匹配。 需要导入 spring-aop的包! 1. 将User类中的set方法去掉,使用@Autowired注解

public class User {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String str;

    public Cat getCat() {
        return cat;
}//加群1025684353一起吹水聊天
    public Dog getDog() {
        return dog;
    }
    public String getStr() {
        return str;
    }
}

2. 此时配置文件内容 领取资料

<bean id="dog" class="com.study.pojo.Dog"/>
<bean id="cat" class="com.study.pojo.Cat"/>
<bean id="user" class="com.study.pojo.User"/>

注意:

//如果允许对象为null,设置required = false,默认为true
@Autowired(required = false)
private Cat cat;

(二)@Qualifier

@Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配 @Qualifier不能单独使用。

1. 配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!

<bean id="dog1" class="com.study.pojo.Dog"/>
<bean id="dog2" class="com.study.pojo.Dog"/>
<bean id="cat1" class="com.study.pojo.Cat"/>
<bean id="cat2" class="com.study.pojo.Cat"/>

2. 没有加Qualifier测试,直接报错 3. 在属性上添加Qualifier注解

@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

(三)、@Resource

@Resource如有指定的name属性,先按该属性进行byName方式查找装配; 其次再进行默认的byName方式进行装配 如果以上都不成功,则按byType的方式自动装配。

1、实体类: 领取资料

public class User {
    //如果允许对象为null,设置required = false,默认为true
    @Resource(name = "cat2")
    private Cat cat;
    @Resource
    private Dog dog;
    private String str;
}

2、beans.xml

<bean id="dog" class="com.study.pojo.Dog"/>
<bean id="cat1" class="com.study.pojo.Cat"/>
<bean id="cat2" class="com.study.pojo.Cat"/>
<bean id="user" class="com.study.pojo.User"/>

测试:结果OK

3、配置文件2:beans.xml , 删掉cat2

<bean id="dog" class="com.study.pojo.Dog"/>
<bean id="cat1" class="com.study.pojo.Cat"/>

4、实体类上只保留注解

@Resource
private Cat cat;
@Resource
private Dog dog;

最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。 可以的话请给我一个三连支持一下我哟,我们下期再见

领取资料