欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring框架学习总结

程序员文章站 2022-07-05 19:22:52
目录spring 框架概述spring优点spring体系结构spring拓展spring boot与spring cloudspring ioc 容器 (ioc 也称为依赖项注入(di),或di是实...

spring 框架概述

  • spring 使创建 java 企业应用程序变得容易。它提供了在企业环境中使用 java 语言所需的一切,并支持 groovy 和 kotlin 作为 jvm 上的替代语言,并且可以根据应用程序的需求灵活地创建多种体系结构。从 spring framework 5.0 开始,spring 需要 jdk 8(java se 8),并且已经为 jdk 9 提供了现成的支持。
  • spring 是分层的 java se/ee full-stack 轻量级开源框架,以 ioc(inverse of control,控制反转)和 aop(aspect oriented programming,面向切面编程)为内核,使用基本的 javabean 完成以前只可能由 ejb 完成的工作,取代了 ejb 臃肿和低效的开发模式。
  • spring 是开源的。它拥有一个庞大而活跃的社区,可以根据各种实际用例提供持续的反馈。这帮助 spring 在很长一段时间内成功地 developing 了。

spring优点

  • 方便解耦,简化开发
  • spring 就是一个大工厂,可以将所有对象的创建和依赖关系的维护交给 spring 管理。
  • 方便集成各大优秀框架
  • spring 不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如 struts2、hibernate、mybatis 等)的直接支持。
  • 方便程序的测试
  • spring 支持 junit4,可以通过注解方便地测试 spring 程序。
  • aop 编程的支持
  • spring 提供面向切面编程,可以方便地实现对程序进行权限拦截和运行监控等功能。
  • 声明式事务的支持
  • 只需要通过配置就可以完成对事务的管理,而无须手动编程。

spring体系结构

spring 框架采用分层架构,根据不同的功能被划分成了多个模块,这些模块大体可分为 data access/integration、web、aop、aspects、messaging、instrumentation、core container 和 test,具体如下图所示:

spring框架学习总结

data access/integration(数据访问/集成)

数据访问/集成层包括 jdbc、orm、oxm、jms 和 transactions 模块,具体介绍如下。

jdbc 模块:提供了一个 jdbc 的抽象层,大幅度减少了在开发过程中对数据库操作的编码。 orm 模块:对流行的对象关系映射 api,包括 jpa、jdo、hibernate 和 ibatis 提供了的集成层。 oxm 模块:提供了一个支持对象/xml 映射的抽象层实现,如 jaxb、castor、xmlbeans、jibx 和 xstream。 jms 模块:指 java 消息服务,包含的功能为生产和消费的信息。 transactions 事务模块:支持编程和声明式事务管理实现特殊接口类,并为所有的 pojo。

web 模块

spring 的 web 层包括 web、servlet、struts 和 portlet 组件,具体介绍如下。

web 模块:提供了基本的 web 开发集成特性,例如多文件上传功能、使用的 servlet 监听器的 ioc 容器初始化以及 web 应用上下文。 servlet模块:包括 spring 模型—视图—控制器(mvc)实现 web 应用程序。 struts 模块:包含支持类内的 spring 应用程序,集成了经典的 struts web 层。 portlet 模块:提供了在 portlet 环境中使用 mv c实现,类似 web-servlet 模块的功能。

core container(核心容器)

spring 的核心容器是其他模块建立的基础,由 beans 模块、core 核心模块、context 上下文模块和 expression language 表达式语言模块组成,具体介绍如下。

beans 模块:提供了 beanfactory,是工厂模式的经典实现,spring 将管理对象称为 bean。 core 核心模块:提供了 spring 框架的基本组成部分,包括 ioc 和 di 功能。 context 上下文模块:建立在核心和 beans 模块的基础之上,它是访问定义和配置任何对象的媒介。applicationcontext 接口是上下文模块的焦点。 expression language 模块:是运行时查询和操作对象图的强大的表达式语言。

其他模块

spring的其他模块还有 aop、aspects、instrumentation 以及 test 模块,具体介绍如下。

aop 模块:提供了面向切面编程实现,允许定义方法拦截器和切入点,将代码按照功能进行分离,以降低耦合性。 aspects 模块:提供与 aspectj 的集成,是一个功能强大且成熟的面向切面编程(aop)框架。 instrumentation 模块:提供了类工具的支持和类加载器的实现,可以在特定的应用服务器中使用。 test 模块:支持 spring 组件,使用 junit 或 testng 框架的测试。

spring拓展

spring boot与spring cloud

  • spring boot 是 spring 的一套快速配置脚手架,可以基于spring boot 快速开发单个微服务。
  • spring cloud是基于spring boot实现的。
  • spring boot专注于快速、方便集成的单个微服务个体,spring cloud关注全局的服务治理框架。
  • spring boot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 , spring cloud很大的一部分是基于spring boot来实现,spring boot可以离开spring cloud独立使用开发项目,但是spring cloud离不开spring boot,属于依赖的关系。
  • springboot在springclound中起到了承上启下的作用,如果你要学习springcloud必须要学习springboot。

spring ioc 容器 (ioc 也称为依赖项注入(di),或di是实现ioc的一种方法)

ioc容器概述

  • 控制反转是一种通过描述(xml或注解)并通过第三方去生产或获取特定对象的方式。在spring中实现控制反转的是ioc容器,其实现方法是依赖注入。
  • spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从ioc容器中取出需要的对象。

spring框架学习总结

  • spring 提供了两种 ioc 容器,分别为 beanfactory 和 applicationcontext。

1.beanfactory

beanfactory是一个factory,用于管理bean的,有了一个spring的beanfactory,我们就可以从spring中获取注册到其中的bean来使用。

2.applicationcontext

applicationcontext 是 beanfactory 的子接口,也被称为应用上下文。该接口的全路径为:

org.springframework.context.applicationcontext,它不仅提供了 beanfactory 的所有功能,还添加了对 i18n(国际化)、资源访问、事件传播等方面的良好支持。

applicationcontext 接口有两个常用的实现类:classpathxmlapplicationcontext和filesystemxmlapplicationcontext。 classpathxmlapplicationcontext从类路径 classpath 中寻找指定的 xml 配置文件,找到并装载完成 applicationcontext 的实例化工作,具体如下所示。applicationcontext applicationcontext = new classpathxmlapplicationcontext(string configlocation);configlocation 参数用于指定 spring 配置文件的名称和位置,如 applicationcontext.xml。

filesystemxmlapplicationcontext从指定的文件系统路径中寻找指定的 xml 配置文件,找到并装载完成 applicationcontext 的实例化工作,具体如下所示。applicationcontext applicationcontext = new filesystemxmlapplicationcontext(string configlocation);它与 classpathxmlapplicationcontext 的区别是:在读取 spring 的配置文件时,filesystemxmlapplicationcontext 不再从类路径中读取配置文件,而是通过参数指定配置文件的位置,它可以获取类路径之外的资源,如“d:/workspaces/applicationcontext.xml”。

3.beanfactory 和 applicationcontext区别:

beanfactory在初始化容器时,并未实例化bean,直到第一次访问某个bean 时才实例目标bean;而applicationcontext 则在初始化应用上下文时就实例化所有单实例的bean 。

在实际开发中,通常都选择使用 applicationcontext,而只有在系统资源较少时,才考虑使用 beanfactory。(但是,它们都是通过 xml 配置文件加载 bean 的。)

spring入门程序

1.创建maven项目

2.在pom.xml导入jar包依赖

    <dependencies>
        <!--导入spring,maven依赖-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-webmvc</artifactid>
            <version>5.2.12.release</version>
        </dependency>
        <!--导入junit-->
        <dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.12</version>
        </dependency>
    </dependencies>

3.编写接口

package com.xxx.mapper;
/**
 * @author shkstart
 * @create 2021-06-11 15:50
 */
public interface usermapper {
    public void hello();
}

4.编写接口实现类

package com.xxx.mapper;/**
 * @author shkstart
 * @create 2021-06-11 15:50
 */
/**
 *@program: springtest
 *@description:
 *@author: xiexianxin
 *@create: 2021-06-11 15:50
 */
public class usermapperimpl implements usermapper{
    @override
    public void hello() {
        system.out.println("spring入门程序!");
    }
}

编写spring核心配置文件applicationcontext.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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--
    使用spring来创建对象,在spring这些都称为bean
    类型 变量名 = new 类型();
    hello hello = new hello();
    id = 变量名
    class = new 的对象
    -->
    <beans>
        <bean id="hello" class="com.xxx.mapper.usermapperimpl">
        </bean>
    </beans>
</beans>

测试

package com.xxx.mapper;/**
 * @author shkstart
 * @create 2021-06-11 15:57
 */
import org.junit.test;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
/**
 *@program: springtest
 *@description:
 *@author: xiexianxin
 *@create: 2021-06-11 15:57
 */
public class hellotest {
    @test
    public void hellotest1(){
        // 1. 初始化spring容器,加载配置文件
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        // 2. 通过容器获取usermapper实例
        usermapper hello = context.getbean("hello", usermapper.class);
        // 3.调用实例中的hello()方法
        hello.hello();

    }
}

测试结果

spring框架学习总结

ioc创建对象的三种方式

通过无参构造(要提供set方法)

编写实体类user:

public class user {
    private string name;
    // set方法
    public void setname(string name) {
        this.name=name;
    }
    public user() {
        system.out.println("无参构造方法执行了!");
    }
    public void print(){
        system.out.println("学生名字为:"+name);
    }
}

编写spring核心配置文件:

<!--无参构造,但是要有set方法-->
        <bean id="user" class="com.xxx.pojo.user">
            <property name="name" value="小新"/>
        </bean>

测试以及结果:

 @test
    public void hellotest2(){
        // 1. 初始化spring容器,加载配置文件
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        // 2. 通过容器获取usermapper实例
        user user = context.getbean("user", user.class);
        // 3.调用实例中的print()方法
        user.print();
    }

spring框架学习总结

通过有参构造(要提供get方法)

编写实体类user:

public class user {
    private string name;
    //get方法
    public string getname() {
        return name;
    }
    public user(string name) {
        system.out.println("有参构造方法执行了!");
        this.name = name;
    }
    public void print(){
        system.out.println("学生名字为:"+name);
    }
}

编写spring核心配置文件:

 <!--有参构造,但是要有get方法-->
        <bean id="user" class="com.xxx.pojo.user">
            <constructor-arg value="小新2" index="0"/>
        </bean>

测试以及结果:

  @test
    public void hellotest2(){
        // 1. 初始化spring容器,加载配置文件
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        // 2. 通过容器获取usermapper实例
        user user = context.getbean("user", user.class);
        // 3.调用实例中的print()方法
        user.print();
    }

spring框架学习总结

拓展:spring核心配置文件有三种写法:

<!--有参构造,但是要有get方法-->
        <bean id="user" class="com.xxx.pojo.user">
            <constructor-arg index="0" value="小新-index属性(0开始,按顺序)"/>
            <constructor-arg name="name" value="小新-name属性"/>
            <constructor-arg type="java.lang.string" value="小新-参数类型"/>
        </bean>

结果展示:

spring框架学习总结

spring框架学习总结

spring框架学习总结

通过工厂类

编写工厂类:

public class factory {
    //方法一,静态方法
    public static user getstaticinstance(){
        return new user("小新2——静态方法创建对象");
    }
    //方法二,实例方法
    public user getinstance(){
        return new user("小新3-实例方法创建对象");
    }
}

编写spring核心配置文件:

<!--工厂类创建对象-->
        <!--创建工厂-->
        <bean id="factory" class="com.xxx.mapper.factory"/>
        <!--静态方法对象-->
        <bean id="staticfactory-user" class="com.xxx.mapper.factory" factory-method="getstaticinstance"/>
        <!--实例方法对象-->
        <bean id="factory-user" factory-bean="factory" factory-method="getinstance"/>

测试以及结果:静态方法:

 @test
    public void hellotest4(){
        // 1. 初始化spring容器,加载配置文件
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        // 2. 通过容器获取usermapper实例
        user user = context.getbean("staticfactory-user", user.class);
        // 3.调用实例中的print()方法
        user.print();
    }

spring框架学习总结

实例方法:

@test
    public void hellotest3(){
        // 1. 初始化spring容器,加载配置文件
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        // 2. 通过容器获取usermapper实例
        user user = context.getbean("factory-user", user.class);
        // 3.调用实例中的print()方法
        user.print();
    }

spring框架学习总结

spring依赖注入(di)和bean的作用域

什么是依赖注入:spring 容器在创建被调用者的实例时,会自动将调用者需要的对象实例注入给调用者,这样,调用者通过 spring 容器获得被调用者实例。

依赖注入主要有两种实现方式,分别是属性 setter 注入和构造方法注入,其中setter注入要求重点掌握。

  • 属性 setter 注入(重点展开讲解)
  • 指 ioc 容器使用 setter 方法注入被依赖的实例。通过调用无参构造器或无参 static 工厂方法实例化 bean 后,调用该 bean 的 setter 方法,即可实现基于 setter 的 di。
  • 构造方法注入
  • 指 ioc 容器使用构造方法注入被依赖的实例。基于构造器的 di 通过调用带参数的构造方法实现,每个参数代表一个依赖。

属性 setter 注入讲解:

环境搭建:(创建一个student和book类):

student

package com.xxx.pojo;/**
 * @author shkstart
 * @create 2021-06-11 17:45
 */
import java.util.*;
/**
 *@program: spring_study
 *@description:
 *@author: xiexianxin
 *@create: 2021-06-11 17:45
 */
public class student {
    private string name;
    private book book;
    private string[] course;
    private list<string> hobbies;
    private map<string,string> card;
    private set<string> fruit;
    private string marriage;
    private properties info;
    public student() {
    }
    public student(string name, book book, string[] course, list<string> hobbies, map<string, string> card, set<string> fruit, string marriage, properties info) {
        this.name = name;
        this.book = book;
        this.course = course;
        this.hobbies = hobbies;
        this.card = card;
        this.fruit = fruit;
        this.marriage = marriage;
        this.info = info;
    }
    @override
    public string tostring() {
        return "student{" +
                "name='" + name + '\'' +
                ", book=" + book +
                ", course=" + arrays.tostring(course) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", fruit=" + fruit +
                ", marriage='" + marriage + '\'' +
                ", info=" + info +
                '}';
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public book getbook() {
        return book;
    }
    public void setbook(book book) {
        this.book = book;
    }
    public string[] getcourse() {
        return course;
    }
    public void setcourse(string[] course) {
        this.course = course;
    }
    public list<string> gethobbies() {
        return hobbies;
    }
    public void sethobbies(list<string> hobbies) {
        this.hobbies = hobbies;
    }
    public map<string, string> getcard() {
        return card;
    }
    public void setcard(map<string, string> card) {
        this.card = card;
    }
    public set<string> getfruit() {
        return fruit;
    }
    public void setfruit(set<string> fruit) {
        this.fruit = fruit;
    }
    public string getmarriage() {
        return marriage;
    }
    public void setmarriage(string marriage) {
        this.marriage = marriage;
    }
    public properties getinfo() {
        return info;
    }
    public void setinfo(properties info) {
        this.info = info;
    }
}

book

package com.xxx.pojo;/**
 * @author shkstart
 * @create 2021-06-11 17:45
 */
/**
 *@program: spring_study
 *@description:
 *@author: xiexianxin
 *@create: 2021-06-11 17:45
 */
public class book {
    private string name;
    private int id;
    public book() {
    }
    @override
    public string tostring() {
        return "book{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public int getid() {
        return id;
    }
    public void setid(int id) {
        this.id = id;
    }
    public book(string name, int id) {
        this.name = name;
        this.id = id;
    }
}

常量注入:

<bean class="com.xxx.pojo.student" id="student">
            <!--常量注入-->
            <property name="name" value="小新"/>
</bean>

bean注入:

<bean class="com.xxx.pojo.book" id="book">
           <property name="name" value="java放弃"/>
           <property name="id" value="100"/>
       </bean>
       <bean class="com.xxx.pojo.student" id="student">
       	 <!--bean注入-->
          <property name="book" ref="book"/>
   	 </bean>

数组注入:

<property name="course">
              <array>
                  <value>高数</value>
                  <value>计算机网络</value>
                  <value>数据库</value>
              </array>
           </property>

list注入:

<property name="hobbies">
               <list>
                   <value>唱</value>
                   <value>跳</value>
                   <value>rap</value>
               </list>
           </property>

map注入:

<property name="card">
               <map>
                   <entry key="银行卡:" value="2501314"/>
                   <entry key="身份证:" value="1314520"/>
               </map>
           </property>

set注入:

 <property name="fruit">
               <set>
                   <value>香蕉</value>
                   <value>苹果</value>
                   <value>雪梨</value>
               </set>
           </property>

null注入:

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

properties注入:

<property name="info">
               <props>
                   <prop key="username">小新</prop>
                   <prop key="password">520</prop>
               </props>
           </property>

测试及结果展示:

public class beantest {
    @test
    public void beantest(){
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        student student = context.getbean("student", student.class);
        system.out.println(student);
    }
}

spring框架学习总结

student{name=‘小新', book=book{name=‘java放弃', id=100}, course=[高数, 计算机网络, 数据库], hobbies=[唱, 跳, rap], card={银行卡:=2501314, 身份证:=1314520}, fruit=[香蕉, 苹果, 雪梨], marriage=‘null', info={password=520, username=小新}}

process finished with exit code 0

p命名空间(以book类举例)导入约束 xmlns:p=“http://www.springframework.org/schema/p”

<bean id="pbook" class="com.xxx.pojo.book" p:name="java懵懂" p:id="250"/>

测试及结果:

 @test
    public void cptest(){
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        book pbook = context.getbean("pbook", book.class);
        system.out.println(pbook);
    }

spring框架学习总结

c命名空间导入约束 xmlns:c=“http://www.springframework.org/schema/c”

<bean id="cbook" class="com.xxx.pojo.book" c:id="520" c:name="java入坑"/>

测试及结果:

  @test
    public void cptest(){
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        book cbook = context.getbean("cbook", book.class);
        system.out.println(cbook);
    }

spring框架学习总结

作用域种类

singleton(以book举例)单例模式,使用 singleton 定义的 bean 在 spring 容器中只有一个实例,这也是 bean 默认的作用域。

<bean class="com.xxx.pojo.book" id="scopebook" scope="singleton">
            <property name="id" value="1"/>
        </bean>
@test
    public void scopetest(){
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        book book1 = context.getbean("scopebook", book.class);
        book book2 = context.getbean("scopebook", book.class);
        system.out.println(book1.hashcode());
        system.out.println(book2.hashcode());
        system.out.println(book1==book2);
    }
}

spring框架学习总结

prototype 原型模式,每次通过 spring 容器获取 prototype 定义的 bean 时,容器都将创建一个新的 bean 实例,即每次调用getbean()时,相当于执行了一次new xxxbean()。

<bean class="com.xxx.pojo.book" id="scopebook" scope="prototype">
            <property name="id" value="1"/>
        </bean>
@test
    public void scopetest(){
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        book book1 = context.getbean("scopebook", book.class);
        book book2 = context.getbean("scopebook", book.class);
        system.out.println(book1.hashcode());
        system.out.println(book2.hashcode());
        system.out.println(book1==book2);
    }
}

spring框架学习总结

  • request

在一次 http 请求中,容器会返回该 bean 的同一个实例。而对不同的 http 请求,会返回不同的实例,该作用域仅在当前 http request 内有效。

  • session

在同一个 http session 中,容器会返回该 bean 的同一个实例。而对不同的 http 请求,会返回不同的实例,该作用域仅在当前 http session 内有效。

  • global session

在一个全局的 http session 中,容器会返回该 bean 的同一个实例。该作用域仅在使用 portlet context 时有效。

spring 常用配置及属性

spring框架学习总结

spring自动装配

  • bean 的装配可以理解为依赖关系注入,bean 的装配方式也就是 bean 的依赖注入方式。spring 容器支持多种形式的 bean的装配方式,如基于 xml 的 bean 装配、基于annotation 的 bean 装配和自动装配等。之前的举例是通过xml的bean装配的。接下来讲解自动装配。
  • 自动装配就是指 spring 容器可以自动装配(autowire)相互协作的 bean 之间的关联关系,将一个 bean 注入其他 bean 的 property 中。
  • spring的自动装配需要从两个角度来实现:

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

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

autowire 的属性和作用

spring框架学习总结

  • 环境搭建:(分别创建一个student和student2类,再创建一个teacher类)
public class student {
   public void study(){
       system.out.println("student类的方法study执行了");
   }
}
public class student2 {
    public void study(){
        system.out.println("student2类的方法study执行了");
    }
}
public class teacher {
    private student student;
    private student2 student2;
    private string teach;
    public teacher() {
    }
    @override
    public string tostring() {
        return "teacher{" +
                "student=" + student +
                ", student2=" + student2 +
                ", teach='" + teach + '\'' +
                '}';
    }
    public student getstudent() {
        return student;
    }
    public void setstudent(student student) {
        this.student = student;
    }
    public student2 getstudent2() {
        return student2;
    }
    public void setstudent2(student2 student2) {
        this.student2 = student2;
    }
    public string getteach() {
        return teach;
    }
    public void setteach(string teach) {
        this.teach = teach;
    }
    public teacher(student student, student2 student2, string teach) {
        this.student = student;
        this.student2 = student2;
        this.teach = teach;
    }
}

配置spring核心配置文件

使用autowire=“byname”:

   <bean class="com.xxx.pojo.student" id="student"/>
 <bean class="com.xxx.pojo.student" id="student"/>
    <bean class="com.xxx.pojo.student2" id="student2"/>
    <bean class="com.xxx.pojo.teacher" id="teacher" autowire="byname">
        <property name="teach" value="java"/>
    </bean>

测试及结果:

public class beantest {
    @test
    public void beantest(){
        applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        teacher teacher = context.getbean("teacher", teacher.class);
        teacher.getstudent().study();
        teacher.getstudent2().study();
    }
}

spring框架学习总结

若修改student的bean id值不为student,如:<bean class="com.xxx.pojo.student" id="s"/>则会报空指针异常java.lang.nullpointerexception at beantest.beantest(beantest.java:24)。因为按byname规则找不对应set方法,真正的setstudent就没执行,对象就没有初始化,所以调用时就会报空指针错误。

当一个bean节点带有 autowire byname的属性时:

1.将查找其类中所有的set方法名,例如setstudent,获得将set去掉并且首字母小写的字符串,即student。

2.去spring容器中寻找是否有此字符串名称id的对象,如果有,就取出注入;如果没有,就报空指针异常。

spring注解开发

环境搭建

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

开启属性注解支持!

<context:annotation-config/>

编写一个 student类

public class student {
    private string name;
    @override
    public string tostring() {
        return "student{" +
                "name='" + name + '\'' +
                '}';
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public student() {
    }
    public student(string name) {
        this.name = name;
    }
}

编写spring核心配置文件:

<bean class="com.xxx.pojo.student" id="student">
       <property name="name" value="小新"/>
   </bean>

测试及结果:

@test
    public void beantest(){
       applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        student student = context.getbean("student",student.class);
        system.out.println(student);

spring框架学习总结

使用@configuration和@bean给容器中注册组件 编写一个配置类

/**
 *@program: springtest
 *@description: 在类上添加@configuration注解使得该类成为spring配置类,通过@bean注解将该类注入到ioc容器,此时配置类==配置文件
 *@author: xiexianxin
 *@create: 2021-06-12 23:06
 */
// 这个配置类也是一个组件
@configuration// 告诉spring这是一个配置类
public class annotationstudent {
    @bean// @bean注解是给ioc容器中注册一个bean,id默认是用方法名作为id
    public student student(){
        return new student("小新");
    }
}

测试及结果:

    @test
    public void beantest(){
        annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(annotationstudent.class);
        student bean = context.getbean(student.class);
        //返回student类在ioc容器中的id值
        string[] namesfortype = context.getbeannamesfortype(student.class);
        for (string s : namesfortype) {
            system.out.println(s);
        }
        system.out.println(bean);
    }
}

spring框架学习总结

若在配置类中给@bean设置一个value值,如@bean("stu")则测试结果为:

spring框架学习总结

则我们在使用注解方式向spring的ioc容器中注入javabean时,如果没有在@bean注解中明确指定bean的名称,那么就会使用当前方法的名称来作为bean的名称;如果在@bean注解中明确指定了bean的名称,那么就会使用@bean注解中指定的名称来作为bean的名称。

使用@componentscan自动扫描组件并指定扫描规则

开启注解扫描,并删除之前配置文件中的bean

<context:component-scan base-package="com.xxx"/>

在原有环境下创建一个com.xxx.service包,并创建一个teacher类,并在类上添加一个@service注解,同时,之前的student类上也添加一个@component注解

@service
public class teacher {
   private student student;
   public void teach(){
       system.out.println("教授的学生是"+student);
   }
    @override
    public string tostring() {
        return "teacher{" +
                "student=" + student +
                '}';
    }
    public student getstudent() {
        return student;
    }
    public void setstudent(student student) {
        this.student = student;
    }
    public teacher(student student) {
        this.student = student;
    }
    public teacher() {
    }
}

测试及结果:

public class beantest {
        @test
        public void beantest() {
            applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
            string[] beandefinitionnames = context.getbeandefinitionnames();
            for (string definitionname : beandefinitionnames) {
                system.out.println(definitionname);
            }
        }
}

spring框架学习总结

以上可以看到:在配置注解扫描后,只要在com.xxx包下的所有子包中,加上了@repository(dao)、@service(service)、@controller、(web)@component注解的类都会被扫描到,并自动注入到spring容器中。(其实上面四个功能,目前为止是一样的)

  • 使用注解配置xml包扫描

我们可以在配置类中(前面的annotationstudent)使用@componentscan注解配置包扫描,由此代替xml中的<context:component-scan base-package="com.xxx"/>。先注释掉之前的xml方式的注解扫描,接着

@configuration// 告诉spring这是一个配置类@componentscan(value = "com.xxx")public class annotationstudent {    @bean// @bean注解是给ioc容器中注册一个bean,id默认是用方法名作为id    public student student(){        return new student("小新");    }}

测试结果跟之前一样。因此,推荐以后都使用注解扫描就好了,spring还是尽量用注解开发,mybatis中还是用xml配置文件。

  • componentscan方法使用

excludefilters()不包含哪些包、includefilters()包含哪些包,使用includefilters时,需要在xml配置文件中先配置use-default-filters="false",即禁用默认的扫描所有包过滤规则才能生效。另外,componentscan还是一个可重复注解的注解,因此可以在一个类上重复使用这个注解。

使用@scope注解设置组件的作用域

通过在类中添加注解@scope注解设置作用域,如:

// 这个配置类也是一个组件
@configuration// 告诉spring这是一个配置类
public class annotationstudent {
    @scope("prototype")
    @bean// @bean注解是给ioc容器中注册一个bean,id默认是用方法名作为id
    public student student(){
        return new student("小新");
    }
}
  • 结果:

如果为false。

  • @scope注解中的取值如下所示:

spring框架学习总结

注解自动装配组件(@resource是jdk自带的)

  • @autowired

@autowired注解可以对类成员变量、方法和构造函数进行标注,完成自动装配的工作。@autowired注解可以放在类、接口以及方法上。等价于<property name="属性名" value=" 属性值"/>@autowired注解默认是优先按照类型去容器中找对应的组件,即:context.getbean(类名.class);,如果找到多个相同类型的组件,那么是将属性名称作为组件的id,到ioc容器中进行查找,即:context.getbean("组件的id");

  • @qualifier

@autowired是根据类型自动装配的,加上@qualifier则可以根据byname的方式自动装配,且qualifier不能单独使用。

  • @resource

是jdk自带的注解 可以按名称注入也可以按类型注入,默认是按名称注入,没有显式指定名称时,在spring容器中匹配与需要注入的bean属性名相同的bean,如果还不同,@resource会找到一个主类型匹配而不是一个特定的命名bean。

懒加载@lazy

懒加载就是spring容器启动的时候,先不创建对象,在第一次使用(获取)bean的时候xxx xxx = context.getbean(xxx.class);再来创建对象,并进行一些初始化。使用时,只需要在配置类的方法上加上@lazy注解即可。

public class annotationstudent {
    @lazy
    @bean// @bean注解是给ioc容器中注册一个bean,id默认是用方法名作为id
    public student student(){
        system.out.println("在容器中添加对象!");
        return new student("小新");
    }
}
public class beantest {
        @test
        public void beantest() {
            applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
            system.out.println("容器创建完成!");
            student student = context.getbean(student.class);
            student student1 = context.getbean(student.class);
            system.out.println(student==student1);
        }
}

spring框架学习总结

  • 非懒加载模式(默认情况):bean在spring容器启动的时候applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");就会被创建,并且还加载到spring容器中去了。
@configuration// 告诉spring这是一个配置类
public class annotationstudent {
    @bean// @bean注解是给ioc容器中注册一个bean,id默认是用方法名作为id
    public student student(){
        system.out.println("在容器中添加对象!");
        return new student("小新");
    }
}
public class beantest {
        @test
        public void beantest() {
            applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
            system.out.println("容器创建完成!");
        }
}

spring框架学习总结

使用@import注解给容器中快速导入一个组件

注册bean的方式通常有以下几种:

1.包扫描+给组件标注注解(@controller、@servcie、@repository、@component

2.@bean注解

3.@import注解(只作用在类上,可以在实际开发项目中导入别人的类并注册到容器中,这是两外两种无法做到的)例如在annotationstudent配置类上导入teacher类对应的bean实例(id默认是组件的全类名)

4.使用factorybean接口(支持泛式)向spring容器中注册bean

// 这个配置类也是一个组件
    @configuration// 告诉spring这是一个配置类
    @import(teacher.class)
    public class annotationstudent {
        @bean// @bean注解是给ioc容器中注册一个bean,id默认是用方法名作为id
        public student student(){
            return new student("小新");
        }
    }
public class beantest {
        @test
        public void beantest() {
           /* applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
            */
            annotationconfigapplicationcontext applicationcontext = new annotationconfigapplicationcontext(annotationstudent.class);
            string[] beannamesfortype = applicationcontext.getbeandefinitionnames();
            for (string s : beannamesfortype) {
                system.out.println(s);
            }
        }
}

spring框架学习总结

当去除@import后,输出结果为:

spring框架学习总结

bean生命周期

常意义上讲的bean的生命周期,指的是bean从创建到初始化,经过一系列的流程,最终销毁的过程,如下图所示。在spring中,我们可以自己来指定bean的初始化和销毁的方法@bean(initmethod = "自定义的初始化方法名",destroymethod = "自定义的销毁方法名")。当容器在bean进行到当前生命周期的阶段时,会自动调用我们自定义的初始化和销毁方法。

spring框架学习总结

自定义一个life类:

public class life {
    public life(){
        system.out.println("life构造方法执行了!");
    }
    public void init(){
        system.out.println("life初始化方法执行了!");
    }
    public void destroy(){
        system.out.println("life销毁方法执行了!");
    }
}

配置类中注册bean:

@configuration// 告诉spring这是一个配置类
    public class annotationstudent {
        @bean(initmethod = "init",destroymethod = "destroy")
        public life life(){
            return new life();
        }
    }

测试及结果:

public class beantest {
        @test
        public void beantest() {
            annotationconfigapplicationcontext applicationcontext = new annotationconfigapplicationcontext(annotationstudent.class);
            system.out.println("容器创建完成!");
            life bean = applicationcontext.getbean(life.class);
        }
}

spring框架学习总结

可以看到,对于单实例对象,先执行构造方法,再到初始化方法,而销毁方法执行需要显式关闭容器时候才执行applicationcontext.close();

spring框架学习总结

因此,我们可以自定义初始化方法和销毁方法处理配置数据源问题,在初始化的时候,会对很多的数据源的属性进行赋值操作;在销毁的时候,我们需要对数据源的连接等信息进行关闭和清理。

@value注解为属性赋值

在student类中的name属性上加上@value注解,等价于配置文件中的<bean id="student" class="com.xxx.pojo.student"> <property name="name" value="xiaoxin"/> </bean>里的<property name="name" value="xiaoxin"/>,外面的bean是@component注解作用。

@component
public class student {
    @value("xiaoxin")
    private string name;
    @override
    public string tostring() {
        return "student{" +
                "name='" + name + '\'' +
                '}';
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public student() {
    }
    public student(string name) {
        this.name = name;
    }
}

测试及结果:

public class beantest {
        @test
        public void beantest() {
            applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
            student student = context.getbean("student", student.class);
            system.out.println(student);
        }
}

spring框架学习总结

使用@propertysource加载配置文件

  • 原始xml方式:
  • 在resources包下创建一个applicationcontext.properties配置文件,内容为键值对形式:name=xiaoxin password=888888
  • 编写一个property类,用于测试:
public class property {
    private string username;
    private integer password;
    @override
    public string tostring() {
        return "property{" +
                "username='" + username + '\'' +
                ", password=" + password +
                '}';
    }
    public string getusername() {
        return username;
    }
    public void setusername(string username) {
        this.username = username;
    }
    public integer getpassword() {
        return password;
    }
    public void setpassword(integer password) {
        this.password = password;
    }
    public property(string username, integer password) {
        this.username = username;
        this.password = password;
    }
    public property() {
    }
}

spring核心配置文件内容为:

    <context:annotation-config />
    <context:component-scan base-package="com.xxx"/>
    <context:property-placeholder location="applicationcontext.properties"/>
    <bean class="com.xxx.pojo.property" id="property">
        <property name="username" value="${name}"/>
        <property name="password" value="${password}"/>
    </bean>

测试及结果:

public class beantest {
        @test
        public void beantest() {
            applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
            property property = context.getbean("property", property.class);
            system.out.println(property.tostring());
        }
}

spring框架学习总结

注解方式:

  • 保留原applicationcontext.properties配置文件
  • 将spring核心配置文件内容删除:只保留开启注解:<context:annotation-config />
  • property类完全使用注解代替:
@configuration//表示该类是配置类,等价于核心配置文件
@componentscan(value = "com.xxx")//等价于<context:component-scan base-package="com.xxx"/>
@component//注册bean,默认id为类名(首字母小写),等价于<bean class="com.xxx.pojo.property" id="property"></bean>
@propertysource("classpath:applicationcontext.properties")//等价于<context:property-placeholder location="applicationcontext.properties"/>
public class property {
    @value("${name}")//等价于<property name="username" value="${name}"/>
    private string username;
    @value("${password}")//等价于<property name="password" value="${password}"/>
    private integer password;
    @override
    public string tostring() {
        return "property{" +
                "username='" + username + '\'' +
                ", password=" + password +
                '}';
    }
    public string getusername() {
        return username;
    }
    public void setusername(string username) {
        this.username = username;
    }
    public integer getpassword() {
        return password;
    }
    public void setpassword(integer password) {
        this.password = password;
    }
    public property(string username, integer password) {
        this.username = username;
        this.password = password;
    }
    public property() {
    }
}

测试及结果:

public class beantest {
        @test
        public void beantest() {
            annotationconfigapplicationcontext applicationcontext = new annotationconfigapplicationcontext(property.class);
            property bean = applicationcontext.getbean(property.class);
            system.out.println(bean.tostring());
        }
}

spring框架学习总结

代理模式

代理模式:为其他对象提供一种代理以控制对这个对象的访问。

spring框架学习总结

spring框架学习总结

spring框架学习总结

静态代理

案例:男孩相亲,想找女孩结婚,于是男孩找媒婆进行代理,媒婆代理介绍女孩同时,还要收取一定的介绍费。

接口类

/**
 *@program: springtest
 *@description: 相亲接口
 *@author: xiexianxin
 *@create: 2021-06-13 20:36
 */
public interface marry {
    //相亲
    void marry();
}

女孩(目标对象)

/**
 *@program: springtest
 *@description: 目标对象
 *@author: xiexianxin
 *@create: 2021-06-13 20:32
 */
public class girl {
    private string name;
    @override
    public string tostring() {
        return "girl{" +
                "name='" + name + '\'' +
                '}';
    }
    public girl(string name) {
        this.name = name;
    }
    public girl() {
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
}

男孩(被代理对象)

/**
 *@program: springtest
 *@description: 被代理对象
 *@author: xiexianxin
 *@create: 2021-06-13 20:33
 */
public class boy implements marry {
    private girl girl;
    public boy(girl girl) {
        this.girl = girl;
    }
    @override
    public void marry() {
        system.out.println("想跟"+girl.getname()+"认识!");
    }
}

媒婆(代理对象)

/**
 *@program: springtest
 *@description: 代理类
 *@author: xiexianxin
 *@create: 2021-06-13 20:33
 */
public class proxy implements marry {
    private boy boy;
    public proxy(girl girl){
         boy = new boy(girl);
    }
    @override
    public void marry() {
        boy.marry();
    }
    public void earn(){
        system.out.println("媒婆收取介绍费");
    }
}

测试及结果

public class proxytest {
    @test
    public void proxytest(){
        girl girl = new girl();
        girl.setname("美女!");
        proxy proxy = new proxy(girl);
        proxy.marry();
        proxy.earn();
    }
}

spring框架学习总结

  • 静态代理的好处:

可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情。

公共的业务由代理来完成 . 实现了业务的分工。

公共业务发生扩展时变得更加集中和方便。

  • 静态代理缺点:

冗余,由于代理对象要实现与目标对象一致的接口,会产生过多的代理类。

不易维护,一旦接口增加方法,目标对象与代理对象都要进行修改。

spring aop aop

aop

(aspect oriented programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。aop是oop的延续,是软件开发中的一个热点,也是spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用aop可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

spring框架学习总结

总的来说,aop是指在程序的运行期间动态地将某段代码切入到指定方法、指定位置进行运行的编程方式。aop的底层是使用动态代理实现的。

aop中相关概念

横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …

切面(aspect):横切关注点 被模块化 的特殊对象。即,它是一个类。

通知(advice):切面必须要完成的工作。即,它是类中的一个方法。

目标(target):被通知对象。

代理(proxy):向目标对象应用通知之后创建的对象。

切入点(pointcut):切面通知 执行的 “地点”的定义。

连接点(jointpoint):与切入点匹配的执行点。

springaop中支持5种类型的advice

spring框架学习总结

spring aop的实现(3种)

  • 导入依赖

在原有的maven的pom.xml文件中加上aop织入依赖包

<!--使用spring实现aop,使用aop织入,需要导入一个依赖包!-->
      <dependency>
          <groupid>org.aspectj</groupid>
          <artifactid>aspectjweaver</artifactid>
          <version>1.9.4</version>
      </dependency>

通过 spring api 实现

编写业务接口及其实现类

/**
 * @author shkstart 第一种,有接口方式,通过 spring api 实现,要实现uservice接口,具体看advice包
 *                  第二种,通过自定义类实现,运用的是aop定义,不需要实现接口,具体看diy包
 *                  第三种,使用注解实现,具体看annotation包
 * @create 2021-06-04 16:12
 */
public interface userservice {
    public void add();
    public void delete();
    public void update();
    public void select();
}
/**
 *@program: spring_study
 *@description:
 *@author: xiexianxin
 *@create: 2021-06-04 16:14
 */
public class userserviceimpl implements userservice{
    @override
    public void add() {
        system.out.println("增加用户");
    }
    @override
    public void delete() {
        system.out.println("删除用户");
    }
    @override
    public void update() {
        system.out.println("更新用户");
    }
    @override
    public void select() {
        system.out.println("查询用户");
    }
}

编写增强类(分别有前置通知、后置通知和环绕通知)

/**
 *@program: spring_study
 *@description: 前置通知,在方法前增强,实现methodbeforeadvice接口
 *@author: xiexianxin
 *@create: 2021-06-04 16:21
 */
public class beforeadvice implements methodbeforeadvice {
    //method : 要执行的目标对象的方法
    //args : 被调用的方法的参数
    //target : 目标对象
    @override
    public void before(method method, object[] args, object target) throws throwable {
        system.out.println("前置通知的"+target.getclass().getname()+"的"+method.getname()+"方法被执行了");
    }
}
/**
 *@program: spring_study
 *@description: 后置通知,在方法后执行,实现afterreturningadvice接口
 *@author: xiexianxin
 *@create: 2021-06-04 17:00
 */
public class afteradvice implements afterreturningadvice {
    //returnvalue 返回值
    //method被调用的方法
    //args 被调用的方法的对象的参数
    //target 被调用的目标对象
    @override
    public void afterreturning(object returnvalue, method method, object[] args, object target) throws throwable {
        system.out.println("后置通知的"+target.getclass().getname()+"的"+method.getname()+"执行了,返回值为:"+returnvalue);
    }
}
/**
 *@program: spring_study
 *@description: 环绕通知,在方法前后执行,实现methodinterceptor接口
 *@author: xiexianxin
 *@create: 2021-06-04 17:07
 */
public class interceptadvice implements methodinterceptor {
    @override
    public object invoke(methodinvocation invocation) throws throwable {
        try {
            system.out.println("环绕通知"+invocation.getmethod().getname()+"——方法前执行的");
            method invocationmethod = (method) invocation.proceed();
            system.out.println("环绕通知"+invocation.getmethod().getname()+"——方法后执行的");
            return invocationmethod;
        } catch (throwable throwable) {
            throwable.printstacktrace();
        }
        return invocation;
    }
}

配置spring核心配置文件,实现aop切入

    <!--第一种方式,通过接口实现-->
    <!--1.注册bean-->
    <bean id="userservice" class="com.xxx.service.userserviceimpl"/>
    <bean id="beforeadvice" class="com.xxx.advice.beforeadvice"/>
    <bean id="afteradvice" class="com.xxx.advice.afteradvice"/>
    <bean id="interceptadvice" class="com.xxx.advice.interceptadvice"/>
    <bean id="throwadvice" class="com.xxx.advice.throwadvice"/>
    <!--2.aop的配置-->
    <aop:config>
        <!--切入点 expression:表达式匹配要执行的方法-->
        <aop:pointcut id="pointcut" expression="execution(* com.xxx.service.userserviceimpl.*(..))"/>
        <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
        <!--前置通知-->
        <aop:advisor advice-ref="beforeadvice" pointcut-ref="pointcut"/>
        <!--后置通知-->
        <aop:advisor advice-ref="afteradvice" pointcut-ref="pointcut"/>
        <!--环绕通知-->
        <aop:advisor advice-ref="interceptadvice" pointcut-ref="pointcut"/>
        <!--异常抛出通知-->
        <aop:advisor advice-ref="throwadvice" pointcut-ref="pointcut"/>
    </aop:config>

测试及结果

public class userserviceimpltest {
    @test
    public void mytest(){
        applicationcontext context = new classpathxmlapplicationcontext("beans.xml");
        //动态代理的是接口,不是实体类,因此不是userserviceimpl.class
        userservice userservice = context.getbean("userservice", userservice.class);
        userservice.delete();
        system.out.println("==============================");
        userservice userservice1 = context.getbean("userservice", userservice.class);
        userservice1.add();
        system.out.println("==============================");
        userservice userservice2 = context.getbean("userservice", userservice.class);
        userservice2.select();
        system.out.println("==============================");
        userservice userservice3 = context.getbean("userservice", userservice.class);
        userservice3.update();
    }
}

spring框架学习总结

通过自定义类来实现 保留之前的业务类userserviceimpl编写自定义类diypointcut

/**
 *@program: spring_study
 *@description: 自定义类实现aop,一个类相当于一个切面,类的方法相当于通知
 *@author: xiexianxin
 *@create: 2021-06-04 21:16
 */
public class diypointcut {
    public void beforeadvice(){
        system.out.println("前置通知");
    }
    public void afteradvice(){
        system.out.println("后置通知");
    }
    public void interceptadvice(proceedingjoinpoint joinpoint){//环绕通知要有proceedingjoinpoint joinpoint参数
        system.out.println("方法"+joinpoint.getsignature().getname()+"环绕通知前执行的语句");
        object[] args = joinpoint.getargs();
        try {
            object proceed = joinpoint.proceed(args);
        } catch (throwable throwable) {
            throwable.printstacktrace();
        }
        system.out.println("方法"+joinpoint.getsignature().getname()+"环绕通知后执行的语句");
    }
}

配置spring核心配置文件

    <!--第二种方式,通过自定义类实现-->
    <!--1.注册bean-->
    <bean id="userservice" class="com.xxx.service.userserviceimpl"/>
    <bean id="diypointcut" class="com.xxx.diy.diypointcut"/>
    <aop:config>
        <!--2.使用aop标签-->
        <aop:aspect ref="diypointcut">
            <!--3.切入点-->
            <aop:pointcut id="pointcut" expression="execution(* com.xxx.service.userserviceimpl.*(..))"/>
            <!--4.通知-->
            <!--前置通知-->
            <aop:before method="beforeadvice" pointcut-ref="pointcut"/>
            <!--后置通知-->
            <aop:after method="afteradvice" pointcut-ref="pointcut"/>
            <!--环绕通知-->
            <aop:around method="interceptadvice" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

测试及结果

public class userserviceimpltest {
    @test
    public void mytest(){
        applicationcontext context = new classpathxmlapplicationcontext("beans.xml");
        //动态代理的是接口,不是实体类,因此不是userserviceimpl.class
        userservice userservice = context.getbean("userservice", userservice.class);
        userservice.delete();
        system.out.println("==============================");
        userservice userservice1 = context.getbean("userservice", userservice.class);
        userservice1.add();
        system.out.println("==============================");
        userservice userservice2 = context.getbean("userservice", userservice.class);
        userservice2.select();
        system.out.println("==============================");
        userservice userservice3 = context.getbean("userservice", userservice.class);
        userservice3.update();
    }
}

spring框架学习总结

通过自定义类来实现 编写注解实现的增强类annotationadvice

/**
 *@program: spring_study
 *@description: 使用注解进行aop设计
 *@author: xiexianxin
 *@create: 2021-06-04 22:18
 */
@aspect
public class annotationadvice {
    @before("execution(* com.xxx.service.userserviceimpl.*(..))")//表达式中写要被增强的类
    public void before(){
        system.out.println("前置通知");
    }
    @after("execution(* com.xxx.service.userserviceimpl.*(..))")
    public void after(){
        system.out.println("后置通知");
    }
    @around("execution(* com.xxx.service.userserviceimpl.*(..))")
    public void around(proceedingjoinpoint joinpoint) throws throwable {
        system.out.println("环绕通知执行前");
        system.out.println("签名:"+joinpoint.getsignature());
        //执行目标方法proceed
        object proceed = joinpoint.proceed();
        system.out.println("环绕通知执行后");
        system.out.println(proceed);
    }
}

开启注解扫描和注册bean

<!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.xxx.service"/>
    <context:annotation-config/>
 <aop:aspectj-autoproxy proxy-target-class="false"/>
    <!--2.注册bean,只需要注册增强的那个类-->
    <bean class="com.xxx.service.userserviceimpl" id="userservice"/>
    <bean id="annotationadvice" class="com.xxx.annotation.annotationadvice"/>

测试及结果

public class userserviceimpltest {
    @test
    public void mytest(){
        applicationcontext context = new classpathxmlapplicationcontext("beans.xml");
        //动态代理的是接口,不是实体类,因此不是userserviceimpl.class
        userservice userservice = context.getbean("userservice", userservice.class);
        userservice.delete();
        system.out.println("==============================");
        userservice userservice1 = context.getbean("userservice", userservice.class);
        userservice1.add();
        system.out.println("==============================");
        userservice userservice2 = context.getbean("userservice", userservice.class);
        userservice2.select();
        system.out.println("==============================");
        userservice userservice3 = context.getbean("userservice", userservice.class);
        userservice3.update();
    }
}

spring框架学习总结

spring事务管理及spring整合mybatis代码示例

spring事务管理

  • 什么是事务:事务就是把一系列的动作当成一个独立的工作单元,这些动作要么都执行,要么都不执行。
  • 事务四个特性-acid:

原子性(atomicity)

事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用

一致性(consistency)

一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中

隔离性(isolation)

可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏

持久性(durability)

事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中spring支持编程

  • 式事务管理和声明式的事务管理:

声明式事务管理

声明式事务管理建立在aop之上,其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,执行完目标方法之后根据执行的情况提交或者回滚。

编程式事务每次实现都要单独实现,但业务量大功能复杂时,使用编程式事务无疑是痛苦的,而声明式事务不同,声明式事务属于无侵入式,不会影响业务逻辑的实现,只需要在配置文件中做相关的事务规则声明或者通过注解的方式,便可以将事务规则应用到业务逻辑中。

显然声明式事务管理要优于编程式事务管理,这正是spring倡导的非侵入式的编程方式。唯一不足的地方就是声明式事务管理的粒度是方法级别,而编程式事务管理是可以到代码块的,但是可以通过提取方法的方式完成声明式事务管理的配置。

使用spring管理事务,注意头文件的约束导入:

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

声明式事务配置拓展:

jdbc事务

<bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
       <property name="datasource" ref="datasource" />
</bean>

自动代理的配置

!-- spring事务管理 -->
<bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
    <property name="datasource" ref="datasource" />
</bean>
<!-- 配置事务的传播特性 -->
<bean id="basetransactionproxy" class="org.springframework.transaction.interceptor.transactionproxyfactorybean" abstract="true" >
  <property name="transactionmanager" ref="transactionmanager" />
  <property name="transactionattributes">
    <props>
      <prop key="add*">propagation_required</prop>
      <prop key="edit*">propagation_required</prop>
      <prop key="remove*">propagation_required</prop>
      <prop key="insert*">propagation_required</prop>
      <prop key="update*">propagation_required</prop>
      <prop key="del*">propagation_required</prop>
      <prop key="*">readonly</prop>
    </props>
  </property>
</bean>

基于 命名空间的声明式事务管理

<beans......>
  ......
  <bean id="bankservice" 
  class="footmark.spring.core.tx.declare.namespace.bankserviceimpl">
    <property name="bankdao" ref="bankdao"/>
  </bean>
  <tx:advice id="bankadvice" transaction-manager="transactionmanager">
    <tx:attributes>
      <tx:method name="transfer" propagation="required"/>
    </tx:attributes>
  </tx:advice>
  <aop:config>
    <aop:pointcut id="bankpointcut" expression="execution(* *.transfer(..))"/>
    <aop:advisor advice-ref="bankadvice" pointcut-ref="bankpointcut"/>
  </aop:config>
  ......
</beans>
  • @transactional 的声明式事务管理

启用tx的annotation:

<tx:annotation-driven transaction-manager="transactionmanager"/>

@transactional 可以作用于接口、接口方法、类以及类方法上。当作用于类上时,该类的所有 public 方法将都具有该类型的事务属性,同时,我们也可以在方法级别使用该标注来覆盖类级别的定义。

编程式事务管理

编程式事务管理是侵入性事务管理,使用transactiontemplate或者直接使用platformtransactionmanager,对于编程式事务管理,spring推荐使用transactiontemplate。

  • spring事务的传播行为:

事务的第一个方面是传播行为(propagation behavior)。当事务方法被另一个事务方法调用时,必须指定事务应该如何传播。例如:方法可能继续在现有事务中运行,也可能开启一个新事务,并在自己的事务中运行。spring定义了七种传播行为:

spring框架学习总结

  • 事务的隔离级别:

事务的第二个维度就是隔离级别(isolation level)。

脏读(dirty reads)——脏读发生在一个事务读取了另一个事务改写但尚未提交的数据时。如果改写在稍后被回滚了,那么第一个事务获取的数据就是无效的。 不可重复读(nonrepeatable read)——不可重复读发生在一个事务执行相同的查询两次或两次以上,但是每次都得到不同的数据时。这通常是因为另一个并发事务在两次查询期间进行了更新。 幻读(phantom read)——幻读与不可重复读类似。它发生在一个事务(t1)读取了几行数据,接着另一个并发事务(t2)插入了一些数据时。在随后的查询中,第一个事务(t1)就会发现多了一些原本不存在的记录。

spring结合事务整合mybatis示例

1.导入相关jar包

<!--spring整合mybatis需要如下包,都是放在dependencies内-->
    <dependencies>
        <!--junit-->
        <dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
            <version>8.0.15</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupid>org.mybatis</groupid>
            <artifactid>mybatis</artifactid>
            <version>3.5.2</version>
        </dependency>
        <!--导入spring,maven依赖-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-webmvc</artifactid>
            <version>5.2.12.release</version>
        </dependency>
        <!--使用spring实现aop,使用aop织入-->
        <dependency>
            <groupid>org.aspectj</groupid>
            <artifactid>aspectjweaver</artifactid>
            <version>1.9.4</version>
        </dependency>
        <!--spring操作数据库也需要一个spring-jdbc包-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-jdbc</artifactid>
            <version>5.3.7</version>
        </dependency>
        <!--整合必要的一个包,mybatis-spring,使用2.0以上版本-->
        <dependency>
            <groupid>org.mybatis</groupid>
            <artifactid>mybatis-spring</artifactid>
            <version>2.0.5</version>
        </dependency>
        <!--log4j-->
        <dependency>
            <groupid>log4j</groupid>
            <artifactid>log4j</artifactid>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupid>org.testng</groupid>
            <artifactid>testng</artifactid>
            <version>release</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupid>log4j</groupid>
            <artifactid>log4j</artifactid>
            <version>1.2.17</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <!--需要解决的乱码以及maven静态资源过滤问题等在build内完成-->
    <!--解决单元测试中文乱码-->
    <build>
        <plugins>
            <plugin>
                <groupid>org.apache.maven.plugins</groupid>
                <artifactid>maven-surefire-plugin</artifactid>
                <version>2.12.4</version>
                <configuration>
                    <argline>
                        -dfile.encoding=utf-8
                    </argline>
                </configuration>
            </plugin>
        </plugins>
        <!--可能出现问题说明:maven静态资源过滤(导出)问题
         cause: org.apache.ibatis.builder.builderexception: error parsing sql mapper configuration.
         cause: java.io.ioexception: could not find resource com/xxx/dao/usermapper.xml
         原因是idea默认不编译src目录下的xml文件,所以加载不到
         解决办法在pom文件中的build标签内加入如下配置,则可以找到java和resources下的所有properties和xml文件了
     -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

2.编写配置文件及加入日志

mybatis-config.xml

<configuration>
    <!--
    configuration" 里的标签顺序如下:(否则报错如下信息)
     "(properties?,settings?,typealiases?,typehandlers?,objectfactory?
     objectwrapperfactory?,reflectorfactory?,plugins?,environments?,
     databaseidprovider?,mappers?)".
    -->
    <!--标准的日志工厂实现(常用:stdout_logging,log4j),下面的value值建议去mybaits文档复制
        日志就是记录程序的运行轨迹,方便查找关键信息,也方便快速定位解决问题。
    -->
    <settings>
        <!--下划线驼峰自动转换-->
        <setting name="mapunderscoretocamelcase" value="true"/>
        <setting name="logimpl" value="log4j"/>
    </settings>
    <!--给这个包下的类起别名-->
    <typealiases>
        <package name="com.xxx.pojo"/>
    </typealiases>
    <mappers>
        <mapper resource="com/xxx/mapper/usermapper.xml"/>
    </mappers>
    
</configuration>

spring-mybatis.xml

<!--
spring整合mybatis,根据mybatis-spring文档可以,需要一个数据源获取sqlsessionfactory 和至少一个数据映射器类
具体查看文档:http://mybatis.org/spring/zh/getting-started.html
-->
    <!--
    datasource:使用spring的数据源替换mybatis的配置:druid c3p0,dbcp
    这里使用speing提供的jdbc:org.springframework.jdbc.datasource.drivermanagerdatasource
    前提是要导入:spring-jdbc 包
    -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">
        <property name="driverclassname" value="com.mysql.cj.jdbc.driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybaits?servertimezone=utc&amp;allowpublickeyretrieval=true&amp;usessl=false&amp;characterencoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!--mybatis-spring 中,可使用 sqlsessionfactorybean来创建 sqlsessionfactory-->
    <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
        <property name="datasource" ref="datasource" />
    <!--跟在mybatis中学习一样,需要在mybatis核心配置文件绑定xxxmapper.xml文件
        这里也需要绑定mybatis核心配置文件,绑定后,mybatis核心配置文件可以完成的这里也都可以完成,则mybatis-config文件可以不要也行
    -->
        <!--绑定mybatis-->
        <property name="configlocation" value="classpath:mybatis-config.xml"/>
        <!--注册映射器,等价于mybatis核心配置文件中的:
            <mappers>
            <mapper resource="com/xxx/mapper/usermapper.xml"/>
            </mappers>
        -->
        <!--<property name="mapperlocations" value="classpath:com/xxx/mapper/*.xml"/>-->
    </bean>
    <!--注册sqlsessiontemplate,相当于我们使用的sqlsession,因此可将id命名为此好记-->
    <bean id="sqlsession" class="org.mybatis.spring.sqlsessiontemplate">
        <!--因为sqlsessiontemplate只有构造方法而无set方法,只能使用构造器注入-->
        <constructor-arg index="0" ref="sqlsessionfactory"/>
    </bean>
    <!--配置声明式事务(aop原理,不改变源代码条件下增加事务),而编程式事务要在源代码上自动try catch
        具体可查看文档:http://mybatis.org/spring/zh/transactions.html
    -->
    <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
        <property name="datasource" ref="datasource"/>
    </bean>
    <!--结合aop实现事务的织入-->
    <!--配置事务的通知-->
    <tx:advice id="transactionadvice" transaction-manager="transactionmanager">
        <!--给具体方法配置事务和传播新特性(propagation=required是默认的,即会自动创建事务)
             具体查看:https://blog.csdn.net/edward0830ly/article/details/7569954
             name="*"表示给所有方法配置事务,也可给具体方法,给出方法名即可
             -->
        <tx:attributes>
            <tx:method name="*" propagation="required"/>
        </tx:attributes>
    </tx:advice>
   <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="transactionpointcut" expression="execution(* com.xxx.mapper.*.*(..))"/>
        <aop:advisor advice-ref="transactionadvice" pointcut-ref="transactionpointcut"/>
    </aop:config>

applicationcontext.xml

 <import resource="spring-mybatis.xml"/>
    <bean id="usermapperimpl_2" class="com.xxx.mapper.usermapperimpl_2">
        <property name="sqlsessionfactory" ref="sqlsessionfactory"/>
    </bean>

log4j.properties

#将等级为debug的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootlogger=debug,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.consoleappender
log4j.appender.console.target = system.out
log4j.appender.console.threshold=debug
log4j.appender.console.layout = org.apache.log4j.patternlayout
log4j.appender.console.layout.conversionpattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.rollingfileappender
log4j.appender.file.file=./log/xxx.log
log4j.appender.file.maxfilesize=10mb
log4j.appender.file.threshold=debug
log4j.appender.file.layout=org.apache.log4j.patternlayout
log4j.appender.file.layout.conversionpattern=[%p][%d{yy-mm-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=debug
log4j.logger.java.sql=debug
log4j.logger.java.sql.statement=debug
log4j.logger.java.sql.resultset=debug
log4j.logger.java.sql.preparedstatement=debug

3.编写接口及其实现类和配置对应的mapper.xml文件

usermapper接口

public interface usermapper {
    //查询所有用户
    public list<user> queryuser();
    //添加一个用户
    int adduser(user user);
    //根据id删除用户
    int deleteuser(int id);
}

usermapperimpl_2实现类

/**
 *@program: spring_study
 *@description: spring-mybatis整合方式二:继承sqlsessiondaosupport实现接口
 *@author: xiexianxin
 *@create: 2021-06-05 22:08
 */
public class usermapperimpl_2 extends sqlsessiondaosupport implements usermapper {
    @override
    public list<user> queryuser() {
        return getsqlsession().getmapper(usermapper.class).queryuser();
    }
    @override
    public int adduser(user user) {
        return getsqlsession().getmapper(usermapper.class).adduser(user);
    }
    @override
    public int deleteuser(int id) {
        return getsqlsession().getmapper(usermapper.class).deleteuser(id);
    }
}

usermapper.xml

<!--namespace==绑定一个对应的dao/mapper接口,以后mapper.xml文件都放在resourse下,
                                            但是要建立一个跟mapper接口相对应得包
    注意!!这里有一个坑,当在resources下建立包时候,不要写为:com.xxx.dao
                                                      应该为:com/xxx/dao
                                           -->
<!--诡异事件,在学习mabatis适合,写utf-8没错,但是整合这里的所有xml却报错:1 字节的 utf-8 序列的字节 1 无效。
    解决方法:将所有的xml文件utf-8改为utf8即可-->
<mapper namespace="com.xxx.mapper.usermapper">
    <!--
    last_name已经进行自动驼峰转换,则这里不用resultmap进行不同名的映射
    resulttype中也起了别名,不用再写com.xxx.pojo了
    -->
    <select id="queryuser" resulttype="user">
        select * from user
    </select>
    <insert id="adduser" parametertype="user">
        insert into user (id,last_name,email) values (#{id},#{lastname},#{email})
    </insert>
    <delete id="deleteuser" parametertype="_int">
        delete from user where id = #{id}
    </delete>
</mapper>

测试及结果

手动设置错误,如在插入语句上写错insert为inserts

  <insert id="adduser" parametertype="user">
        inserts into user (id,last_name,email) values (#{id},#{lastname},#{email})
    </insert>
public class usermappertest {
    static logger logger = logger.getlogger(usermappertest.class);
    @test
   @test
    public void usermapperimpl_2(){
       applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
        usermapper usermapperimpl_2 = context.getbean("usermapperimpl_2", usermapper.class);
        usermapperimpl_2.adduser(new user(12,"xiaoxin","com@xiaoxin"));
        usermapperimpl_2.deleteuser(8);
        for (user user : usermapperimpl_2.queryuser()) {
            system.out.println(user);
        }
    }
}

如果为插入语句错误,则项目不能正常插入,事务会回滚。

spring框架学习总结

查看并刷新数据库表,没有变化。

spring框架学习总结

接着将错误改正后,再次测试结果为:

spring框架学习总结

成功添加和删除,事务保证了数据的一致性。查看数据库表为:

spring框架学习总结

总结

本篇文章的内容就到这了,希望大家可以喜欢,也希望大家可以多多关注的其他精彩内容!

相关标签: spring 学习总结