Spring

1.1 简介

  • 2002,首次推出了Spring框架的雏形:interface21框架
  • Spring框架以interface21框架为基础,经过重新设计,并不断丰富其内涵,与2004年3月24日发布了1.0正式版。
  • Rod Johnson,spring framework创始人
  • spring理念:使现有的技术更加容易的使用,本身是一个大杂烩

官网:https://docs.spring.io/spring-framework/docs/current/reference/html/index.html

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.2</version>
</dependency>

1.2 优点

  • spring是一个开源的免费的框架(容器)
  • spring是一个轻量级的,非入侵的框架
  • 控制反转(IOC),面向切面编程(AOP)
  • 支持事务的处理,对框架整合的支持

总结:spring是一个轻量级的控制反转(IOC)和面向切面编程的框架

1.3 组成

spring简单使用【入门】_spring

1.4 拓展

基于Spring的开发

spring简单使用【入门】_spring_02

  • springboot
    • 一个快速开发的教授兼
    • 基于springboot可以快速的开发单个诶服务
    • 约定大于配置
  • springCloud
    • springcloud是基于springboot实现的

因为现在大多数公司都在使用springboot开发进行快速开发,学习springboot的前提需要完全掌握spring和springmvc!承上启下的作用

弊端:发展太久,违背了原来的理念,配置十分繁琐,人称“配置地狱”

2 IOC

控制反转IoC(Inversion of Control)是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。所谓控制反转就是获得一个对象的方式反转了。

控制反转是一种通过描述(XML或者注解)并通过第三方去生产或获取特定对象的方式,在spring中实现控制反转的是Ioc容器,其实现方法是依赖注入(Dependency Injection,DI)

不需要更改程序,如果想实现不同的操作只需要在xml配置文件中进行修改。也就是一切对象交给spring创建、管理、装配

3 HelloSpring
package com.mjoe.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}
<?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="hello" class="com.mjoe.pojo.Hello">
        <property name="str" value="SpringFirst"/>
    </bean>
    
</beans>
import com.mjoe.pojo.Hello;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = (Hello)classPathXmlApplicationContext.getBean("hello");
        System.out.println(hello.toString());
    }
}
4 IOC创建对象的全部方式

默认为单例模式,可通过scope修改创建模式作用域

4.1 默认使用无参构造函数创建对象,通过setter注入

package com.mjoe.pojo;

public class User {

    private String name;

    public User() {
        System.out.println("User的无参构造器被调用");
    }

    public String getName() {
        return name;
    }

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

    public void show(){
        System.out.println("name="+name);
    }
}
<?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="user" class="com.mjoe.pojo.User">
        <property name="name" value="mjoe"/>
    </bean>

</beans>

4.2 使用有参构造函数创建对象有三种传参方式

package com.mjoe.pojo;

public class User {

    private String name;

    public User(String name) {
        this.name = name;
        System.out.println("User的有参构造器被调用");
    }

    public void show(){
        System.out.println("name="+name);
    }
}

4.2.1 下标

<?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="user" class="com.mjoe.pojo.User">
        <constructor-arg index="0" value="mjoe"/>
    </bean>

</beans>

4.2.2  参数类型

<?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="user" class="com.mjoe.pojo.User">
        <constructor-arg type="java.lang.String" value="mjoe"/>
    </bean>

</beans>

4.2.3 参数名

<?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="user" class="com.mjoe.pojo.User">
        <constructor-arg name="name" value="mjoe"/>
    </bean>

</beans>
5 配置

5.1 别名

<alias name="user" alias="dkfjldjflds"/>  //不常用
    <bean id="user" class="com.mjoe.pojo.User" name="kdfdjkfld u2,u3"> //name 可以同时起多个别名,通过空格或者逗号分隔
        <constructor-arg name="name" value="mjoe"/>
    </bean>

5.2 import

这个import一般用于团队开发,可以将多个配置文件导入合并为一个

假设,当前项目有多个人同时开发,不同的人负责不同类的开发,不同的类就需要注册在不同的bean中,可以利用import将所有人的beans.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">

    <import resource="beans.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
</beans>
public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
        User user = (User) context.getBean("u2");
        User user2 = (User) context.getBean("u3");
        user.show();
        System.out.println(user==user2);
    }
}
6 依赖注入

6.1 通过构造器注入

4.2

6.2 Set方式注入【重点】

  • 依赖注入:set注入!
    • 依赖:bean对象的创建交给容器
    • 注入:bean对象中的所有属性,由容器来注入!

【环境搭建】

package com.mjoe.pojo;

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
package com.mjoe.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> game;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

    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> getGame() {
        return game;
    }

    public void setGame(Set<String> game) {
        this.game = game;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", game=" + game +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}
<?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="address" class="com.mjoe.pojo.Address">
        <property name="address" value="中国"/>
    </bean>

    <bean id="student" class="com.mjoe.pojo.Student">

<!--        1. 普通值注入,value-->
        <property name="name" value="mjoe"/>

<!--        2. bean注入,ref-->
        <property name="address" ref="address"/>

<!--        3. 数组注入 array标签-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>三国演义</value>
                <value>水浒传</value>
            </array>
        </property>

<!--        List-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
            </list>
        </property>

<!--        map-->
        <property name="card">
            <map>
                <entry key="身份证" value="4343434343434"/>
                <entry key="银行卡" value="444333434958844030"/>
            </map>
        </property>

<!--        set-->
        <property name="game">
            <set>
                <value>Lol</value>
                <value>COC</value>
            </set>
        </property>

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

        <property name="info">
            <props>
                <prop key="学号">43483</prop>
                <prop key="url">nan</prop>
            </props>
        </property>
    </bean>


</beans>
import com.mjoe.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) applicationContext.getBean("student");
        System.out.println(student.toString());
    }
}
Student{
name='mjoe', 
address=Address{address='中国'}, 
books=[红楼梦, 西游记, 三国演义, 水浒传], 
hobbys=[听歌, 敲代码], 
card={身份证=4343434343434, 银行卡=444333434958844030}, 
game=[Lol, COC], 
wife='null', 
info={学号=43483, url=nan}}

6.3 拓展方式注入

6.3.1 p命名空间注入(无参构造set简写)

约束

xmlns:p="http://www.springframework.org/schema/p"

注入

<bean id="user" class="com.mjoe.pojo.User" p:name="mjoe" p:age="18"/>

6.3.2 c命名空间注入(有参构造简写)

约束

xmlns:c="http://www.springframework.org/schema/c"

注入

<bean id="user2" class="com.mjoe.pojo.User" c:age="18" c:name="mjo2"/>

6.4 作用域

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

6.4.1 单例模式(Spring默认)

<bean id="user" class="com.mjoe.pojo.User" p:name="mjoe" p:age="18" scope="singleton"/>

spring简单使用【入门】_spring_03

6.4.2 原型模式

<bean id="user2" class="com.mjoe.pojo.User" c:age="18" c:name="mjo2" scope="prototype"/>

spring简单使用【入门】_spring_04

7 Bean的自动装配
  • 自动装配只是Spring满足Bean依赖注入的一种方式
  • Spring会自动的在上下文寻找,并自动的给bean装备属性

在Spring中有三种装配方式:

  1. 在xml中显式的装配
  2. 在java中显式的装配
  3. 隐式的自动装配bean【重要】

7.1  测试环境(一个人两宠物)

package com.mjoe.pojo;

public class Person {
    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.mjoe.pojo;

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

public class Cat {
    public void shout(){
        System.out.println("miao~");
    }
}
<?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.mjoe.pojo.Dog"/>
    <bean id="cat" class="com.mjoe.pojo.Cat"/>

    <bean id="person" class="com.mjoe.pojo.Person">
        <property name="name" value="mjoe"/>
        <property name="dog" ref="dog"/>
        <property name="cat" ref="cat"/>
    </bean>
</beans>

7.2 ByName

自动匹配   该对象set方法传入的参数名(也就是通过private封装的属性名)  和   bean配置上下文文件中所定义的bean名,如果相同,则自动装配

<bean id="person" class="com.mjoe.pojo.Person" autowire="byName">
    <property name="name" value="mjoe"/>
</bean>

7.3 ByType

自动匹配   该对象set方法传入的参数类型(通过private封装的属性类型)  和   bean配置上下文文件中所定义的bean的类型,如果相同,则自动装配

<bean id="person" class="com.mjoe.pojo.Person" autowire="byType">
    <property name="name" value="mjoe"/>
</bean>

小结:

  • byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
  • bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

7.4 使用注解实现自动装配

jdk1.5 支持注解,Spring2.5支持注解

使用注解须知:

  1. 导入约束
  2. 配置注解的支持 context:annotation-config/
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

@Autowired

直接在属性上使用即可(也可以不用编写set方法了)(通过ByName)

package com.mjoe.pojo;

import org.springframework.beans.factory.annotation.Autowired;

public class Person {
    @Autowired
    private Cat cat;

    @Autowired
    @Qualifier(value=“xxx”)
    private Dog dog;


    private String name;

    public Cat getCat() {
        return cat;
    }

    public Dog getDog() {
        return dog;
    }


    public String getName() {
        return name;
    }

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

Tips:

@Nullable    如果某个字段标记了这个注解,就代表这个字段可以为null

如果@Autowired自动装配的环境很复杂,无法通过一个@Autowired完成的时候,可以使用@Qualifier(value=“xxx”)配合使用,这样就可以指定为一个bean对象注入

@Resource

java本身带的ByName和ByType的集合体(先默认通过name,再通过type)

@Resource(name = "cat2")
private Cat cat;
8 使用注解开发

在spring4之后,要使用注解开发,必须保证AOP的包导入。

spring简单使用【入门】_spring_05

使用注解需要导入context的约束,增加注解的支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--    指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.mjoe"/>
<!--    注解驱动-->
    <context:annotation-config/>

</beans>

8.1 bean

8.2 属性怎么注入

package com.mjoe.dao;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class User {

    @Value("mjoe")
    public String name;
}

8.3 衍生的注解

@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层

  • dao【@Repository】
  • service 【@Service】
  • controller【@Controller】

这四个注解功能一样,都代表将某个类注册到spring中,装配一个bean

8.4 自动装配置

@Configuration

8.5 作用域

@Scope("singelon"/"prototype")

8.6 小结

xml与注解

  • xml更加万能,适用于任何场合,维护方便
  • 注解不是自己的类不能使用
9 使用java的方式配置Spring

javaConfig 代替xml,配置类

10 代理模式11 AOP12 整合Mybatis

12.1 导包

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.2</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>

    
</dependencies>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    mybatis配置文件还是留一些-->
    <typeAliases>
        <package name="com.mjoe.pojo"/>
    </typeAliases>
    
</configuration>

spring整合Mybatis文件(spring-dao.xml),整合完成无法直接使用,需要第三方类来使用这个整合文件配置

spring-jdbc数据源管理(用谁家的都行)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--    DataSource:使用Spring的数据源替换Mybatis的数据源-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="ma269095"/>
    </bean>

<!--    sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
<!--        可以绑定mybatis的一些配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/mjoe/mapper/*.xml"/>
    </bean>

<!--    SqlSessionTemplate就是mybatis中使用的sqlSession,只是命名习惯问题-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

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

    <import resource="spring-dao.xml"/>

    <bean id="userMapperImpl" class="com.mjoe.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

    <bean id="UserMapperImpl2" class="com.mjoe.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

Tips:需要第三方类

package com.mjoe.mapper;

import com.mjoe.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> selectUser();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mjoe.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from mybatis.user;
    </select>
</mapper>
package com.mjoe.mapper;

import com.mjoe.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper{
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

也可使用SqlSessionDaoSupport

package com.mjoe.mapper;

import com.mjoe.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> selectUser() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}
13 声明式事务

13.1 事务

  • 把一组业务当成一个业务来做;要嘛都成功,要嘛都失败
  • 事务在项目开发中十分重要,涉及到数据的一致性问题
  • 确保完整性和一致性

事务ACID原则:

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能操作同一个资源,防止数据损坏
  • 持久性
    • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中

13.2 声明式事务AOP

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--    结合AOP实现事务的织入-->
<!--    配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        给哪些方法配置事务-->
<!--        配置事务的传播特性: propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

<!--    配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.mjoe.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
hema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--    结合AOP实现事务的织入-->
<!--    配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        给哪些方法配置事务-->
<!--        配置事务的传播特性: propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

<!--    配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.mjoe.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>