Spring

本文深入探讨了Spring框架的核心特性,包括IoC(控制反转)和DI(依赖注入)的概念及其实现,如XML配置、无参构造、有参构造等创建对象的方式。此外,还介绍了SpringBoot的快速开发特性以及SpringCloud在微服务中的应用。文章详细讲解了Spring中bean的配置、作用域以及自动装配,特别是注解的使用。AOP(面向切面编程)部分阐述了代理模式、切点表达式以及环绕增强,并展示了Spring如何实现事务管理,包括编程式和声明式事务。最后,提到了Spring与Mybatis的整合以及事务管理在实际项目中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Spring5

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

1.1、IoC思想

  • Inversion(反转) Of Control:控制反转
  • IoC的原型:通过set方法进行动态实现值的注入
  • 依赖注入(Dependency Injection,DI)是实现IoC的一种方法

资源获取的方式:

​ 主动式:通过主动创建资源来获取资源

BookServlet{
    BookService bs = new BookService();
    AirPlane ap = new AirPlane();//复杂对象的创建是比较庞大的工程
}

​ 被动式:资源的获取不是通过自己创建,而是交给一个容器来创建和设置

BookServlet{
    BookService bs;
    public void test1()_{
        bs.checkout();
    }
}

容器:

  • 从主动地去new资源变为被动地接受资源
  • 以前是new对象,现在所有的对象交给容器来创建,给容器中注册组件

1.2、拓展

  • Spring Boot
    • 一个快速开发的脚手架
    • 基于Spring bo
    • ot可以快速开发单个微服务
    • 约定大于配置
  • Spring Cloud
    • Spring Cloud是基于Spring boot实现的

2.配置xml方法实现Hello Spring

1.新建Maven工程,导入Spring

<!--pom.xml-->
<dependencies>
    <dependency>
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.0.RELEASE</version><!--版本-->
    </dependency>
</dependencies>

2.新建Hello类,设置set方法

public class Hello {
    private String name;

    //set注入是实现Spring容器管理对象的方法
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

3.新建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">

</beans>
<!--/模板-->

<?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
	id:对象名
	class:要创建的类
	property:
		value:给对象的属性设置一个值
		ref:引用Spring容器中创建好的对象,值为其他bean的id
	-->
    <bean id="hello" class="com.luffy.spring.Hello">
        <property name="name" value="Hello Spring"/>
    </bean>

</beans>

4.测试

public class Test {
    public static void main(String[] args) {
        //获取Spring的上下文对象,拿到Spring容器***
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        
        //使用getBean(String)方法从Spring中获取对象
        Hello hello=(Hello)context.getBean("hello");
        System.out.println(hello.getName());
    }
}

3.IoC创建对象的方式

  • 默认使用无参构造创建对象

  • 有参构造创建对象方法:

    方法一:下标赋值

    <bean id="hello" class="com.luffy.spring.Hello">
        <constructor-arg index="0" value="xxx"/>
        <constructor-arg index="1" value="xxx"/>
    </bean>

​ 方法二:通过类型赋值,不建议使用

 <bean id="hello" class="com.luffy.spring.Hello">
        <constructor-arg type="java.lang.String" value="xxx"/>
        <constructor-arg type="int" value="xxx"/>
    </bean>

​ 方法三:直接通过参数名,最直观

 <bean id="hello" class="com.luffy.spring.Hello">
        <constructor-arg name="name" value="xxx"/>
        <constructor-arg name="sex" value="xxx"/>
    </bean>

总结:在配置文件beans.xml加载的时候,容器中管理的对象就已经全部初始化了!

4.Spring相关配置

<!-- 1.别名,可以通过这个别名获取到这个对象-->
<alias name="user" alias="newUser"/>

<!-- 2.bean配置
 	使用Spring来创建对象,在Spring中这些都称为bean
	id:对象名
	class:要创建的类
	property:
		value:给对象的属性设置一个值
		ref:引用Spring容器中创建好的对象,值为其他bean的id
	name:别名,可以同时取多个别名
-->

<!-- 3.import,一般用于团队开发,在配置文件中导入其他的配置文件-->
<import resource="beans2.xml"/>

5.依赖注入(Dependency Injection)

5.1 构造器注入

即有参构造方式,参照3

5.2 Set方式注入

  • 复杂对象注入示例
//创建复杂对象类
import java.util.*;

public class Student {
    private String name;
    private String sex;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    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> 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> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    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 + '\'' +
                ", sex='" + sex + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}
class Address {
}
<!--配置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">

    <bean id="address" class="com.luffy.spring.Address"></bean>
 <bean id="student" class="com.luffy.spring.Student">
     <!--普通值注入-->
     <property name="name" value="luffy"/>
     <!--空值注入-->
     <property name="sex" value=""/>
     <!--bean注入-->
     <property name="address" ref="address"/>
     <!--数组注入-->
     <property name="books">
         <array>
             <value>西游记</value>
             <value>三国演义</value>
             <value>水浒传</value>
         </array>
     </property>
     <!--list注入-->
     <property name="hobbies">
         <list>
             <value></value>
             <value></value>
             <value>Rap</value>
             <value>打篮球</value>
         </list>
     </property>
     <!--Map注入-->
     <property name="card">
         <map>
             <entry key="IDCard" value="330xxxxxxxxxxxxxxx"/>
             <entry key="ICCard" value="llfxxxxxx"/>
         </map>
     </property>
     <!--Set注入-->
     <property name="games">
         <set>
             <value>LOL</value>
         </set>
     </property>
     <!--null值注入-->
     <property name="wife">
         <null/>
     </property>
     <!--Properties注入-->
     <property name="info">
         <props>
             <prop key="author">luffy</prop>
             <prop key="email">lou1274012686@qq.com</prop>
         </props>
     </property>
 </bean>

</beans>
//测试
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

5.3 拓展方式注入

c命名空间和p命名空间注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       <!--导入c命名和p命名空间-->
		xmlns:p="http://www.springframework.org/schema/p"
		xmlns:c="http://www.springframework.org/schema/c"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--p命名空间注入,可以直接注入属性的值,property-->
<bean id="user" class="com.luffy.spring.User" p:name="luffy" p:age="20"/>
<!--c命名空间注入,通过构造器注入,constructor-args-->
<bean id="user2" class="com.luffy.spring.User2" c:name="luffy" c:age="20"/>
</beans>

5.4 bean作用域

<bean scope="singleton"/>
  • singleton 单例模式(Spring默认机制):容器中只会存在一个该对象
  • prototype 原型模式:每次从容器中get的时候,都会产生一个新的对象
  • request、session、application:只在web开发中使用到

6.bean自动装配

Spring中三种bean装配的方式:

​ 1.在xml中显式地配置

​ 2.在Java中显式地配置

​ 3.隐式地自动装配bean(重要)

  • byType/byName自动装配

    <bean id="xxx" class="xxx" autowire="byType/byName"
    byName:自动在容器中找set方法后面的值对应的bean id,区分大小写
    byType:查找类型相同的bean,只能全局唯一     
    

6.1使用注解实现自动装配

使用注解须知:

  • 导入约束:context约束
  • 配置注解的支持 <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
           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:annotation-config/>
   <bean id="xxx" class="xxxxxxx"></bean>
       
</beans>
相关注解
  • @Autowired:直接在属性上使用即可,可以不用编写set方法;
  • @Nullable:字段标注了这个注解,说明了这个字段可以为null;
  • @Qualifier(value=“xxx”):与@autowired配合使用,存在多个同类对象时,使用@Qualifier(value=“xxx”)来指定唯一的bean对象
  • @Resource:Java自带的自动装配
@Resource和@Autowired的区别
  • 都是自动装配,都可以放在属性字段上
  • @Autowired通过Bytype方式查找,找不到再通过Byname
  • @Resource通过Byname方式查找,找不到再通过Bytype

7.使用注解开发

7.1 bean

要保证aop包的导入,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 ">
    <!--component-scan:指定要扫描的目录,目录下的注解就会生效-->
    <context:component-scan base-package="com.luffy.pojo"/>
    <context:annotation-config/>

</beans>

7.2 属性如何注入

  • @Component:组件,放在类上,说明这个类被Spring管理了

  • @Value(“xxx”):放在属性上,直接通过注解给属性赋值

package com.luffy.pojo;

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

@Component
public class Student {
    @Value("luffy")
    private String name;
    private String id;
    @Autowired
    private Teacher teacher;


    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", teacher=" + teacher +
                '}';
    }
}

7.3 衍生的注解

  • @Component有几个衍生注解,在web开发中,会按照mvc三层架构分层
    • dao层:@Repository
    • service层:@Service
    • controller层:@Controller

7.6 小结

  • xml更加万能,适用于任何场合,维护简单
  • 注解不是自己的类不能使用,维护相对复杂

8.代理模式

实现业务分工

在不改变源码的情况下,对原有功能进行增强

一个真实角色就会产生一个或多个代理角色,代码量会翻倍

  • 静态代理
    • 抽象角色:一般会用接口或者抽象类来解决
    • 真实角色:被代理的角色
    • 代理角色:代理真实角色,代理真实角色后,做一些附属操作
    • 客户:访问代理对象
  • 动态代理

动态代理的代理类是动态生成的,不是直接写好的

分为两大类:基于接口的动态代理,基于类的动态代理

基于接口:jdk动态代理

基于类:cglib

java字节码实现:javasist

9.AOP

使用spring实现AOP,需要导入AOP织入包

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

方式一:使用Spring的接口

1.添加log类

2.service接口及实现类

3.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"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context
           http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="com.luffy.service.UserServiceImpl"/>
    <bean id="log" class="com.luffy.logs.Log"/>
    <bean id="aferReturnLog" class="com.luffy.logs.AfterReturnLog"/>

    <!--方式一:使用SpringAPI接口-->
    <!--配置aop-->
    <aop:config>
        <!--切入点:expression:表达式,execution(要执行的位置)-->
        <aop:pointcut id="pointcut" expression="execution(* com.luffy.service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="aferReturnLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

4.测试

import com.luffy.service.UserService;
import com.luffy.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userService=context.getBean("userService", UserService.class);
        userService.add();
    }
}

方式二:自定义类实现AOP,切面定义

1.自定义切面DiyPointCut.java

package com.luffy.diy;

public class DiyPointCut {
    public void before(){
        System.out.println("===before===");
    }

    public void after(){
        System.out.println("===after===");
    }
}

2.applicationContext.xml进行配置

    <!--方式二:自定义类-->
    <!--配置aop-->
    <bean id="diy" class="com.luffy.diy.DiyPointCut"/>
    <aop:config>
        <!--自定义切面,ref 引用的切面类-->
        <aop:aspect ref="diy">
            <aop:pointcut id="point" expression="execution(* com.luffy.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

3.测试输出

===before===
add
===after===

方式三:使用注解实现AOP

1.定义注解切面

package com.luffy.diy;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//使用注解实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.luffy.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("before===");
    }
}

2.applicationContext.xml中配置

<!--方式三:注解实现AOP-->
<bean id="annotationPointCut" class="com.luffy.diy.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>

3.测试

//扩展

//在环绕增强中,可以给定一个参数,代表要获取处理切入的点

@Around("execution(* com.luffy.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
   System.out.println("环绕前===");
   Object proceed=jp.proceed();//执行方法
   System.out.println("环绕后===");
}

10.Spring整合Mybatis

10.1 maven导入依赖

junit,mybatis,mysql,spring,aop,mybatis-spring

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring-mybatis01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--spring操作数据库还需要spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
    </dependencies>

</project>

10.2 核心配置文件

1.编写实体类

在com.luffy.pojo目录下新建User类

package com.luffy.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;
}

2.编写核心配置文件

spring-dao.xml(代替mybatis-config.xml,通过spring整合mybatis的方式交互数据)

<?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"
       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/context
           http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://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.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="0129"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:com/luffy/mapper/*.xml"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能用构造器注入sqlSessionFactory,因为template没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

mybatis-config.xml,简单的一些mybatis设置

<?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>
    <!--标准的日志工厂-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
</configuration>

applicationContext.xml,为具体的bean注册

<?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"
       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/context
           http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <import resource="spring-dao.xml"/>

    <!--具体的bean注册-->


</beans>

3.编写接口

UserMapper.java

package com.luffy.dao;

import com.luffy.pojo.User;

import java.util.List;

public interface UserMapper {
    public List<User> selectUser();
}

4.编写Mapper.xml

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.luffy.dao.UserMapper">
    <select id="selectUser" resultType="com.luffy.pojo.User">
        select * from mybatis_demo.user;
    </select>
</mapper>

5.测试

import com.luffy.mapper.UserMapper;
import com.luffy.pojo.User;
import com.luffy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class test01 {
    @Test
    public void test(){
        //先从spring容器取sqlSessionTemplate对象,再通过sqlSession获取UserMapper
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        SqlSessionTemplate sqlSessionTemplate=context.getBean("sqlSessionTemplate",SqlSessionTemplate.class);
        //这是是手动实现了UserMapper接口进行使用,或者可以在spring中注册UserMapper的实现类,然后直接调用
        UserMapper userMapper= sqlSessionTemplate.getMapper(UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
}

11.Spring的事务管理

  • 事务ACID原则

    • 原子性
    • 隔离性
    • 持久性
    • 一致性
  • spring中的事务管理分为:

    • 编程式事务管理
    • 声明式事务管理,AOP

11.1配置声明式事务管理

结合AOP实现事务的织入,不影响原来的业务

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"
       xmlns:context="http://www.springframework.org/schema/context"
       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/tx
           http://www.springframework.org/schema/spring-tx.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <import resource="spring-dao.xml"/>
    <!--结合AOP实现事务的织入-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置事务的传播特性:propagation-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务的切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.luffy.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
    <!--具体的bean注册-->


</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值