Spring-IOC


一、IOC容器

1.1 IOC思想

IOC:Inversion of Control,翻译过来是反转控制

①获取资源的传统方式
自己做饭:买菜、洗菜、择菜、改刀、炒菜,全过程参与,费时费力,必须清楚了解资源创建整个过程中的全部细节且熟练掌握。
在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效率。

②反转控制方式获取资源
点外卖:下单、等、吃,省时省力,不必关心资源创建过程的所有细节。
反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向——改由容器主动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式。

③DI
DI:Dependency Injection,翻译过来是依赖注入。
DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。相对于IOC而言,这种表述更直接。

所以结论是:IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现。

1.2 IOC容器在Spring中的实现

Spring 的 IOC 容器就是 IOC 思想的一个落地的产品实现。IOC 容器中管理的组件也叫做bean。在创建bean 之前,首先需要创建 IOC 容器。Spring 提供了 IOC 容器的两种实现方式:
①BeanFactory
这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。
②ApplicationContext
BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用
ApplicationContext 而不是底层的 BeanFactory。
③ApplicationContext的主要实现类
在这里插入图片描述
在这里插入图片描述

二、基于XML管理bean

2.1 入门案例

①创建Maven Module

②引入依赖

<dependencies>
<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>5.3.1</version>
	</dependency>
	
<!-- junit测试 -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>
</dependencies>

在这里插入图片描述
③创建类HelloWorld

public class HelloWorld {
	public void sayHello(){
		System.out.println("helloworld");
	}
}

④创建Spring的配置文件
在这里插入图片描述
在这里插入图片描述

⑤在Spring的配置文件中配置bean

<!--
配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
通过bean标签配置IOC容器所管理的bean
属性:
	id:设置bean的唯一标识
	class:设置bean所对应类型的全类名
-->
<bean id="helloworld" class="com.atguigu.spring.bean.HelloWorld"></bean>

⑥创建测试类测试

@Test
public void testHelloWorld(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	HelloWorld helloworld = (HelloWorld) ac.getBean("helloworld");
	helloworld.sayHello();
}

⑦思路
在这里插入图片描述
⑧注意
Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name
‘helloworld’ defined in class path resource [applicationContext.xml]: Instantiation of bean
failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed
to instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nested
exception is java.lang.NoSuchMethodException: com.atguigu.spring.bean.HelloWorld.()

2.2 获取bean的三种方式

①方式一:根据id获取
由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。上个实验中我们使用的就是这种方式。

Student studentOne = (Student) ioc.getBean("studentOne");

②方式二:根据类型获取 (常用)

Student student = ioc.getBean(Student.class);

③方式三:根据id和类型

Student student = ioc.getBean("studentOne",Student.class);

④注意

 * 获取bean的三种方式:
 * 1、根据bean的id获取
 * 2、根据bean的类型获取
 * 注意:根据类型获取bean时,要求IOC容器中有且只有一个类型匹配的bean
 *若没有任何一个类型匹配的bean,此时抛出异常:NoSuchBeanDefinitionException
 *若有多个类型匹配的bean,此时抛出异常:NoUniqueBeanDefinitionException
 * 3、根据bean的id和类型获取
 * 结论:
 * 根据类型来获取bean时,在满足bean唯一性的前提下,
 * 其实只是看:对象instanceof指定的类型 的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。
 * 即通过bean的类型、bean所继承的类的类型、bean所实现的接口的类型都可以获取bean

2.3 依赖注入之setter注入

<!--set注入赋值-->
    <bean id="studentTwo" class="com.atguigu.spring.pojo.Student">
        <!--使用的是SetXxx()方法 属性就是在SetGet方法中 然后把方法名中的SetGet去掉
        剩余的首字母变成小写的结果就是属性-->
        <!--
            property:通过成员变量的set方法进行赋值
            name:设置需要赋值的属性名(和set方法有关)
            value:设置为属性所赋的值
        -->
        <property name="sid" value="1001"></property>
        <property name="sname" value="张三"></property>
        <property name="age" value="23"></property>
        <property name="gender" value="男"></property>
    </bean>

2.4 依赖注入之构造器注入

constructor-arg标签还有两个属性可以进一步描述构造器参数:
index属性:指定参数所在位置的索引(从0开始)
name属性:指定参数名

<!--构造器注入赋值-->
    <bean id="studentThree" class="com.atguigu.spring.pojo.Student">
        <constructor-arg value="1002"></constructor-arg>
        <constructor-arg value="李四"></constructor-arg>
        <constructor-arg value="女"></constructor-arg>
        <constructor-arg value="24" name="age"></constructor-arg>
    </bean>

2.5 特殊值处理

①字面量赋值

什么是字面量?
int a = 10;
声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a
的时候,我们实际上拿到的值是10。
而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面
量。所以字面量没有引申含义,就是我们看到的这个数据本身。

<!-- 使用value属性给bean的属性赋值时,Spring会把value属性的值看做字面量 -->
<property name="name" value="张三"/>

②null值

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

注意:

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

以上写法,为name所赋的值是字符串null

③xml实体

<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替
		<:&lt;
        >:&gt;
-->
<property name="expression" value="a &lt; b"/>

④CDATA节

<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>

2.6 为类类型属性赋值

为类类型的属性赋值有三种方法:
1.引用外部bean: ref :引用IOC容器中的某个bean的id
2.级联的方式,要保证提前为cLazz属性赋值或者实例化
3.内部bean,只能在当前bean的内部使用,不能直接通过IoC容器获取

 <bean id="studentFive" class="com.atguigu.spring.pojo.Student">
        <property name="sid" value="1004"></property>
        <property name="sanme" value="赵六"></property>
        <property name="age" value="26"></property>
        <property name="gender" value="男"></property>
        <!-- ref :引用IoC容器中的某个bean的id- -->
        <!--<property name="clazz" ref="clazzOne"></property>-->
         <!-- 级联的方式,要保证提前为cLazz属性赋值或者实例化 用的不多-->
        <!--<property name="clazz.cid" value="2222"></property>
        <property name="clazz.cname" value="远大前程班"></property>-->

        <property name="clazz">
            <!--内部bean,只能在当前bean的内部使用,不能直接通过IoC容器获取 -->
            <bean id="clazzInner" class="com.atguigu.spring.pojo.Clazz">
                <property name="cid" value="2222"></property>
                <property name="cname" value="远大前程班"></property>
            </bean>
        </property>
</bean>

<bean id="clazzOne" class="com.atguigu.spring.pojo.Clazz">
        <property name="cid" value="1111"></property>
        <property name="cname" value="嘴强王者班"></property>
    </bean>

2.7 为数组类型属性赋值

在property中用array标签进行赋值
value进行字面量赋值
ref进行引用赋值

<bean id="studentFour" class="com.atguigu.spring.bean.Student">
	<property name="id" value="1004"></property>
	<property name="name" value="赵六"></property>
	<property name="age" value="26"></property>
	<property name="sex" value="女"></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
	<property name="clazz" ref="clazzOne"></property>
	<property name="hobbies">
		<array>
          <value>打篮球</value>
          <value>打羽毛球</value>
          <value>打排球</value>
		</array>
	</property>
</bean>

2.8 为集合类型属性赋值

2.8.1 为list集合类型的属性赋值

第一种:标签下用标签中的标签引用bean类型
第二种:利用util:list 写一个外部标签 在引入 要注意的是util:list要新增约束

<bean id="clazzOne" class="com.atguigu.spring.pojo.Clazz">
        <property name="cid" value="1111"></property>
        <property name="cname" value="嘴强王者班"></property>
        <!--<property name="students">
            1.
            <list>
                <ref bean="studentOne"></ref>
                <ref bean="studentTwo"></ref>
                <ref bean="studentThree"></ref>
            </list>
        </property>-->
        <property name="students" ref="studentList"></property>
    </bean>

<!--2.配置一个List集合类型的bean,需要使用util的约束-->
 <util:list id="studentList">
        <ref bean="studentOne"></ref>
        <ref bean="studentTwo"></ref>
        <ref bean="studentThree"></ref>
    </util:list>

2.8.2 为Map集合类型属性赋值

第一种:标签下用标签中的标签中的key,value-ref进行赋值
第二种:利用util:map 写一个外部标签 再引入赋值

<!--Map类型属性赋值-->
        <property name="teacherMap" ref="teacherMap"></property>
        <!--<property name="teacherMap">
            1.<map>
                &lt;!&ndash;一个entry就是一个键值对&ndash;&gt;
                <entry key="10086" value-ref="teacherOne"></entry>
                <entry key="10010" value-ref="teacherTwo"></entry>
            </map>
        </property>-->

	<bean id="teacherOne" class="com.atguigu.spring.pojo.Teacher">
        <property name="tid" value="10086"></property>
        <property name="tname" value="大宝"></property>
    </bean>
    <bean id="teacherTwo" class="com.atguigu.spring.pojo.Teacher">
        <property name="tid" value="10010"></property>
        <property name="tname" value="小宝"></property>
    </bean>

<!--2.配置一个Map类型的bean,需要使用util的约束-->
    <util:map id="teacherMap">
        <entry key="10086" value-ref="teacherOne"></entry>
        <entry key="10010" value-ref="teacherTwo"></entry>
    </util:map>

2.9 p命名空间

<!--bean的属性-p命名空间赋值-->
    <bean id="studentSix" class="com.atguigu.spring.pojo.Student"
          p:sid="1005" p:sname="小明" p:teacherMap-ref="teacherMap"></bean>

2.10 引入外部属性文件

①引用连接数据库的文件首先加入依赖,要注意MySQL驱动的版本

<!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

②其次是创建外部属性文件jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_user?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

③在spring配置文件中引入属性文件,并配置bean

<!--引入jdbc.properties,之后可以通过${key}的方式访问value-->
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>

    </bean>

2.11 bean的作用域

①概念
在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:
在这里插入图片描述
如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):
在这里插入图片描述
②配置bean

<!--
        scope:设置bean的作用域
        scope="singleton"(单例):表示获取该bean所对应的对象都是同一个
        scope="prototype"(多例):表示获取该bean所对应的对象都不是同一个
    -->
    <bean id="student" class="com.atguigu.spring.pojo.Student" scope="prototype">
        <property name="sid" value="1001"></property>
        <property name="sname" value="张三"></property>
    </bean>

2.12 bean的生命周期

①具体的生命周期过程

bean对象创建(调用无参构造器)
给bean对象设置属性
bean对象初始化之前操作(由bean的后置处理器负责)
bean对象初始化(需在配置bean时指定初始化方法)
bean对象初始化之后操作(由bean的后置处理器负责)
bean对象就绪可以使用
bean对象销毁(需在配置bean时指定销毁方法)
IOC容器关闭

②详细介绍

  bean的生命周期:
  1、实例化
  2、依赖注入
  3、后置处理器的postProcessBeforeInitialization
  4、初始化,需要通过bean的init-method属性指定初始化的方法
  5、后置处理器的postProcessAfterInitialization
  6、IOC容器关闭时销毁,需要通过bean的destroy-method属性指定销毁的方法
 
  bean的后置处理器会在生命周期的初始化前后添加额外的操作
  需要实现BeanPostProcessor接口且配置到IOC容器中
  需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行
 
 注意:
 若bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时执行
 若bean的作用域为多例时,生命周期的前三个步骤会在获取bean时执行,但是销毁就不会执行,此时就不归IOC容器管了

③修改类User

public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
System.out.println("生命周期:1、创建对象");
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
System.out.println("生命周期:2、依赖注入");
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void initMethod(){
System.out.println("生命周期:3、初始化");
}
public void destroyMethod(){
System.out.println("生命周期:5、销毁");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}

这里是引用

④配置bean

<!-- 使用init-method属性指定初始化方法 -->
<!-- 使用destroy-method属性指定销毁方法 -->

	<bean id="user" class="com.atguigu.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod">
        <property name="id" value="1"></property>
        <property name="username" value="小明"></property>
        <property name="password" value="123"></property>
        <property name="age" value="20"></property>
    </bean>

⑤测试
在测试类中获取ioc容器要用configurableApplicationcontext而不是Applicationcontext,因为configurableApplicationcontext是Applicationcontext的子接口,其中扩展了刷新和关闭容器的方法,只有这样才能关闭容器

@Test
     public void test(){
        //ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
        ioc.close();
    }

⑥bean的后置处理器
bean的后置处理器会在生命周期的初始化前后添加额外的操作
需要实现BeanPostProcessor接口:

package com.atguigu.spring.process;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MybeanPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //此方法在bean的生命周期初始化之前执行
        System.out.println("MyBeanPostProcessor-->后置处理器postProcessBeforeInitialization");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //此方法在bean的生命周期初始化之后执行
        System.out.println("MyBeanPostProcessor-->postProcessAfterInitialization");
        return bean;
    }
}


且配置到IOC容器中:

<!-- bean的后置处理器要放入IOC容器才能生效 -->
<bean id="myBeanProcessor" class="com.atguigu.spring.process.MyBeanProcessor"/>

需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容
器中所有bean都会执行

2.13 FactoryBean

①简介
FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个
FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。

② FactoryBean是一个接口,需要创建一个类实现该接口
其中有三个方法:

  • getObject():通过一个对象交给IOC容器管理
  • getObjectType():设置所提供对象的类型
  • isSingleton():所提供的对象是否单例

当把FactoryBean的实现类配置为bean时,会将当前类中getObject()所返回的对象交给IOC容器管理

public class UserFactoryBean implements FactoryBean<User> {
    public User getObject() throws Exception {
        return new User();
    }

    public Class<?> getObjectType() {
        return User.class;
    }

    public boolean isSingleton() {
        return false;
    }
}

③配置bean

<bean class="com.atguigu.spring.factory.UserFactoryBean"></bean>

2.14 基于xml的自动装配

自动装配:
根据指定的策略,在IOC容器中匹配某个bean,自动为bean中类类型的属性或接口类型的属性赋值
可以通过bean标签中的autowire属性设置自动装配的策略
自动装配的策略:
1、no,default:表示不装配,即bean中的属性不会自动匹配某个bean为属性赋值,此时属性使用默认值
2、byType:根据要赋值的属性的类型,在IOC容器中匹配某个bean,为属性赋值
注意:
a>若通过类型没有找到任何一个类型匹配的bean,此时不装配,属性使用默认值
b>若通过类型找到了多个类型匹配的bean,此时会抛出异常:NoUniqueBeanDefinitionException
总结:当使用byType实现自动装配时,IOC容器中有且只有一个类型匹配的bean能够为属性赋值
3、byName:将要赋值的属性的属性名作为bean的id在IOC容器中匹配某个bean,为属性赋值

配置bean

<bean id="userController" class="com.atguigu.spring.controller.UserController" autowire="byName">
        <!--<property name="userService" ref="userService"></property>-->
    </bean>

    <bean id="userService" class="com.atguigu.spring.service.impl.UserServiceImpl" autowire="byName">
        <!--<property name="userDao" ref="userDao"></property>-->
    </bean>

    <bean id="Service" class="com.atguigu.spring.service.impl.UserServiceImpl" autowire="byName">
        <!--<property name="userDao" ref="userDao"></property>-->
    </bean>

    <bean id="userDao" class="com.atguigu.spring.dao.impl.UserDaoImpl"></bean>

    <bean id="Dao" class="com.atguigu.spring.dao.impl.UserDaoImpl"></bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值