Spring基础——Spring初识、SringIOC容器、Spring Bean

一、Spring是什么
Spring是一个主流的JavaWEB的开发容器,是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架

二、Spring的主要优点
1)方便解耦,简化开发
Spring 就是一个大工厂,可以将所有对象的创建和依赖关系的维护交给 Spring 管理。
2)方便集成各种优秀框架
Spring 不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如 Struts2、Hibernate、MyBatis 等)的直接支持。
3)降低 Java EE API 的使用难度
Spring 对 Java EE 开发中非常难用的一些 API(JDBC、JavaMail、远程调用等)都提供了封装,使这些 API 应用的难度大大降低。
4)方便程序的测试
Spring 支持 JUnit4,可以通过注解方便地测试 Spring 程序。
5)AOP 编程的支持
Spring 提供面向切面编程,可以方便地实现对程序进行权限拦截和运行监控等功能。
6)声明式事务的支持
只需要通过配置就可以完成对事务的管理,而无须手动编程。

三、SpringIOC
IOC(inversion of control):控制反转, 是指在程序开发中,实例的创建不再由调用者管理,而是由 Spring 容器创建。Spring 容器会负责控制程序之间的关系,而不是由程序代码直接控制,因此,控制权由程序代码转移到了 Spring 容器中,控制权发生了反转,这就是 Spring 的 IoC 思想,Spring 提供了两种 IoC 容器,分别为 ApplicationContext和 BeanFactory。

四、什么是Spring Bean
Spring bean是Spring框架在运行时管理的对象。Spring bean是任何Spring应用程序的基本构建块。我们编写的大多数应用程序逻辑代码都将放在Spring bean中。

五、建立第一个Spring程序,Bean对象的实例化
1).创建一个测试类

package springtest;

public class Animal {
    private String name;
    private int num;
    public Animal(){}

    public Animal(String name, int num) {
        this.name = name;
        this.num = num;
    }

    public String getName() {
        return name;
    }

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

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", num=" + num +
                '}';
    }
}

2).创建Spring配置文件
在 resource目录下创建 Spring 的核心配置文件 applications.xml(复制粘贴就行了)编辑后如下所示。

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
          <!-- 这是我们要进行操作的地方-->
 </beans>

3).用Spring来创建Animal类的对象

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
         <bean id="animal1" class="springtest.Animal">
        <constructor-arg name="name" value="张三"></constructor-arg>
        <constructor-arg name="num" value="1"></constructor-arg>
    </bean>
 </beans>

表示在 Spring 容器中创建一个 id 为 animal1 的 bean 实例,其中 id 表示文件中的唯一标识符,class 属性表示指定需要实例化 Bean 的实全限定类名(包名+类名)。

4).对Spring创建的对象进行测试

public static void main(String[] args) {
			 // 初始化Spring容器,加载配置文件,并对bean进行实例化
          ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml");
			// 通过容器获取Animal实例
          Animal animal1=(Animal) context.getBean("animal1");
			//输出创建Spring创建的Animal对象
          System.out.println(animal1);

    }

5).运行结果

Animal{name='张三', num=1}

Process finished with exit code 0

六、DI(依赖注入)
DI(Dependency Injection):依赖注入,和控制反转含义相同,它们是从两个角度描述的同一个概念。Spring 容器在创建被调用者的实例时,会自动将调用者需要的对象实例注入给调用者,这样,调用者通过 Spring 容器获得被调用者实例,这称为依赖注入。
依赖注入的两种方式:
1).通过构造方法
指 IoC 容器使用构造方法注入被依赖的实例。基于构造器的 DI 通过调用带参数的构造方法实现,每个参数代表一个依赖。
示例:
在配置文件中创建一个String的实例,并在animal2对象实例中向name属性中注入id=myName,ref关键字应用于引用某个实例

 <bean id="myName" class="java.lang.String">
        <constructor-arg value="李四" />
    </bean>
 <bean id="animal2" class="springtest.Animal">
        <constructor-arg name="name" ref="myName"></constructor-arg>
        <constructor-arg name="num" value="2"></constructor-arg>
   </bean>

测试一下:

public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml");

          Animal animal2=(Animal) context.getBean("animal2");

          System.out.println(animal2);

    }

name属性被成功赋值了:

Animal{name='李四', num=2}

Process finished with exit code 0

2).通过setter方法注入bean的属性,通过配置
指 IoC 容器使用 setter 方法注入被依赖的实例。通过调用无参构造器或无参 static 工厂方法实例化 bean 后,调用该 bean 的 setter 方法,即可实现基于 setter 的 DI。

<bean id="myName" class="java.lang.String">
        <constructor-arg value="李四" />
    </bean>
 <bean id="animal3" class="springtest.Animal">
        <property name="name" ref="myName"/>
        <property name="num" value="3"/>
    </bean>

测试一下:

 public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml");

          Animal animal3=(Animal) context.getBean("animal3");

          System.out.println(animal3);

    }

运行结果:

Animal{name='李四', num=3}

Process finished with exit code 0

Spring Bean元素的常用属性
作为 Spring 核心机制的依赖注入,改变了传统的编程习惯,对组件的实例化不再由应用程序完成,转而交由 Spring 容器完成,在需要时注入应用程序中,从而对组件之间依赖关系进行了解耦。这一切都离不开 Spring 配置文件中使用的 元素。
Spring 容器可以被看作一个大工厂,而 Spring 容器中的 Bean 就相当于该工厂的产品。如果希望这个大工厂能够生产和管理 Bean,这时则需要告诉容器需要哪些 Bean,以及需要以何种方式将这些 Bean 装配到一起。
Spring 配置文件支持两种不同的格式,分别是 XML 文件格式和 Properties 文件格式。
通常情况下,Spring 会以 XML 文件格式作为 Spring 的配置文件,这种配置方式通过 XML 文件注册并管理 Bean 之间的依赖关系。
XML 格式配置文件的根元素是 <beans>,该元素包含了多个 bean 子元素,每一个 bean子元素定义了一个 Bean,并描述了该 Bean 如何被装配到 Spring 容器中。
在这里插入图片描述

八、Spring Bean的作用域
Spring 容器在初始化一个 Bean 的实例时,同时会指定该实例的作用域。Spring3 为 Bean 定义了五种作用域,具体如下。
1)singleton
单例模式,使用 singleton 定义的 Bean 在 Spring 容器中只有一个实例,这也是 Bean 默认的作用域。
2)prototype
原型模式,每次通过 Spring 容器获取 prototype 定义的 Bean 时,容器都将创建一个新的 Bean 实例。
3)request
在一次 HTTP 请求中,容器会返回该 Bean 的同一个实例。而对不同的 HTTP 请求,会返回不同的实例,该作用域仅在当前 HTTP Request 内有效。
4)session
在一次 HTTP Session 中,容器会返回该 Bean 的同一个实例。而对不同的 HTTP 请求,会返回不同的实例,该作用域仅在当前 HTTP Session 内有效。
5)global Session
在一个全局的 HTTP Session 中,容器会返回该 Bean 的同一个实例。该作用域仅在使用 portlet context 时有效。

在上述五种作用域中,singleton 和 prototype 是最常用的两种,接下来将对这两种作用域进行详细讲解。

1.singleton
singleton 是 Spring 容器默认的作用域,当一个 Bean 的作用域为 singleton 时,Spring 容器中只会存在一个共享的 Bean 实例,并且所有对 Bean 的请求,只要 id 与该 Bean 定义相匹配,就只会返回 Bean 的同一个实例。
通常情况下,这种单例模式对于无会话状态的 Bean(如 DAO 层、Service 层)来说,是最理想的选择
在 Spring 配置文件中,可以使用 <bean> 元素的 scope 属性,将 Bean 的作用域定义成 singleton,其配置方式如下所示:

<bean id="animal1" class="springtest.Animal" scope="singleton"/>

当然singleton为默认作用域,可以不用scope声明
测试一下:

 public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml");
          Animal animal1=(Animal) context.getBean("animal1");
          Animal animal2=(Animal) context.getBean("animal1");
          System.out.println("animal1和animal2是否为同一对象:"+(animal1==animal2));
    }

运行结果:

animal1和animal2是否为同一对象:true

Process finished with exit code 0

2.)prototype
使用 prototype 作用域的 Bean 会在每次请求该 Bean 时都会创建一个新的 Bean 实例。因此对需要保持会话状态的 Bean(如 Struts2 的 Action 类)应该使用 prototype 作用域。

在 Spring 配置文件中,要将 Bean 定义为 prototype 作用域,只需将 <bean> 元素的 scope 属性值定义成 prototype,其示例代码如下所示:

<bean id="animal1" class="springtest.Animal" scope="prototype*"/>

测试一下:

 public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml");
          Animal animal1=(Animal) context.getBean("animal1");
          Animal animal2=(Animal) context.getBean("animal1");
          System.out.println("animal1和animal2是否为同一对象:"+(animal1==animal2));
    }

结果:

animal1和animal2是否为同一对象:false

Process finished with exit code 0

九、Spring Bean的生命周期
Spring容器可以管理 singleton 作用域 Bean 的生命周期,在此作用域下,Spring 能够精确地知道该 Bean 何时被创建,何时初始化完成,以及何时被销毁。
而对于 prototype 作用域的 Bean,Spring 只负责创建,当容器创建了 Bean 的实例后,Bean 的实例就交给客户端代码管理,Spring 容器将不再跟踪其生命周期。每次客户端请求 prototype 作用域的 Bean 时,Spring 容器都会创建一个新的实例,并且不会管那些被配置成 prototype 作用域的 Bean 的生命周期。
了解 Spring 生命周期的意义就在于,可以利用 Bean 在其存活期间的指定时刻完成一些相关操作。这种时刻可能有很多,但一般情况下,会在 Bean 被初始化后和被销毁前执行一些相关操作。
在 Spring 中,Bean 的生命周期是一个很复杂的执行过程,我们可以利用 Spring 提供的方法定制 Bean 的创建过程。
当一个 Bean 被加载到 Spring 容器时,它就具有了生命,而 Spring 容器在保证一个 Bean 能够使用之前,会进行很多工作。Spring 容器中 Bean 的生命周期流程如图 下图所示。
在这里插入图片描述
Bean 生命周期的整个执行过程描述如下。

1)根据配置情况调用 Bean 构造方法或工厂方法实例化 Bean。

2)利用依赖注入完成 Bean 中所有属性值的配置注入。

3)如果 Bean 实现了 BeanNameAware 接口,则 Spring 调用 Bean 的 setBeanName() 方法传入当前 Bean 的 id 值。

4)如果 Bean 实现了 BeanFactoryAware 接口,则 Spring 调用 setBeanFactory() 方法传入当前工厂实例的引用。

5)如果 Bean 实现了 ApplicationContextAware 接口,则 Spring 调用 setApplicationContext() 方法传入当前 ApplicationContext 实例的引用。

6)如果 BeanPostProcessor 和 Bean 关联,则 Spring 将调用该接口的预初始化方法 postProcessBeforeInitialzation() 对 Bean 进行加工操作,此处非常重要,Spring 的 AOP 就是利用它实现的。

7)如果 Bean 实现了 InitializingBean 接口,则 Spring 将调用 afterPropertiesSet() 方法。

8)如果在配置文件中通过 init-method 属性指定了初始化方法,则调用该初始化方法。

9)如果 BeanPostProcessor 和 Bean 关联,则 Spring 将调用该接口的初始化方法 postProcessAfterInitialization()。此时,Bean 已经可以被应用系统使用了。

10)如果在 <bean> 中指定了该 Bean 的作用范围为 scope=“singleton”,则将该 Bean 放入 Spring IoC 的缓存池中,将触发 Spring 对该 Bean 的生命周期管理;如果在 <bean> 中指定了该 Bean 的作用范围为 scope=“prototype”,则将该 Bean 交给调用者,调用者管理该 Bean 的生命周期,Spring 不再管理该 Bean。

11)如果 Bean 实现了 DisposableBean 接口,则 Spring 会调用 destory() 方法将 Spring 中的 Bean 销毁;如果在配置文件中通过 destory-method 属性指定了 Bean 的销毁方法,则 Spring 将调用该方法对 Bean 进行销毁。

Spring 为 Bean 提供了细致全面的生命周期过程,通过实现特定的接口或 <bean> 的属性设置,都可以对 Bean 的生命周期过程产生影响。虽然可以随意配置 <bean> 的属性,但是建议不要过多地使用 Bean 实现接口,因为这样会导致代码和 Spring 的聚合过于紧密。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值