Spring框架笔记

本文详细介绍了Spring框架的核心概念,包括IoC(控制反转)、AOP(面向切面编程)以及依赖注入的多种方式。讲解了Bean的作用域、自动装配、注解开发和Java配置类的使用。还涉及了Spring中的代理模式,包括静态和动态代理,并探讨了Spring AOP在事务管理中的应用。最后,文章提到了Spring整合Mybatis和Spring事务管理的配置方法。
摘要由CSDN通过智能技术生成

Spring概念

  • spring是开源的免费的框架(容器)

  • spring是轻量级的,非侵入式的

  • spring核心主要两部分 :

AOP : 面向切面编 ,扩展功能不是修改源代码实现 .

IOC : 控 制 反 转 ,比 如 有 一 个 类 , 在 类 里 面 有 方 法 ( 不 是 静 态 的 方 法 ) , 调 用 类 里 面 的 方 法 , 创 建 类 的 对 象 , 使 用 对 象 调 用 方 法 , 创 律 类 对 象 的 过 程 , 需 要 new 出 来 对 象 . 把 对 象 的 创 建 不 是 通 过 “ new 方 式 实 现 , 而 是 交 给 、 spring 配 置 创 建 类 对 象 .

组成

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EmTgIzlW-1593686235330)(Spring框架.assets/image-20200702183348012.png)]

IoC

控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。 没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

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

控制:谁来控制对象的创建,Spring来控制。

反转:程序本身不创建对象,被动接受对象。

依赖注入:对象需要有属性的setter方法,或有参数的构造方法,Spring通过配置文件内容进行属性值的注入。

对象由spring进行创建,管理,装配。

IOC创建对象

1.默认使用无参构造创建对象。

2.有参构造

@Data
public class User {
    private String str;

    User(String s) {
        str = s;
    }
}
通过下标
<bean id="User" class="com.User">
    <!--通过构造器参数个数,下标从零开始赋值-->
    <constructor-arg index="0" value="syg"/>
</bean>
通过类型
<bean id="User" class="com.User">
    <constructor-arg type="java.lang.String" value="syg"/>
</bean>
通过参数名
<bean id="User" class="com.User">
    <constructor-arg name="s" value="syg"/>
</bean>

在IOC容器创建后,里面的所有bean都会被创建。

Baen

bean起别名

通过name,且可以起多个,通过逗号或空格或分号分隔
<bean id="User" class="com.User" name="User2,u2 u3;u4">
    <constructor-arg name="s" value="syg"/>
</bean>
//通过alias
<alias name="User" alias="user"/>

import

可以将多个配置文件导入到一个配置文件中。

在另一个xml配置文件中导入其他的配置文件,可以导入多个
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="beans.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
</beans>

依赖注入

set方法进行注入

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

复杂类型对象

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

真实对象

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", info=" + info +
                ", wife='" + wife + '\'' +
                '}';
    }
    ...下面包含set,get方法
}

beans.xml

<bean id="address" class="com.pojo.Address">
    <property name="address" value="乌鲁木齐"/>
</bean>
<bean id="student" class="com.pojo.Student">
    <!--普通注入-->
    <property name="name" value="syg"/>
    <!--bean注入-->
    <property name="address" ref="address"/>
    <!--数组注入-->
    <property name="books">
        <array>
            <value>红楼梦</value>
            <value>西游记</value>
            <value>水浒传</value>
            <value>三国演义</value>
        </array>
    </property>
    <!--list注入-->
    <property name="hobbies">
        <list>
            <value>乒乓球</value>
            <value>崩坏3</value>
            <value>看电影</value>
        </list>
    </property>
    <!--map-->
    <property name="card">
        <map>
            <entry key="身份证" value="112332231"/>
            <entry key="银行卡" value="2132132312"/>
        </map>
    </property>
    <!--set-->
    <property name="games">
        <set>
            <value>崩坏3</value>
            <value>穿越火线</value>
        </set>
    </property>
    <!--空-->
    <property name="wife">
        <null/>
    </property>

    <property name="info">
        <props>
            <prop key="学号">2017100</prop>
            <prop key="性别"></prop>
            <prop key="昵称">香榭的落叶</prop>
        </props>
    </property>
</bean>

测试类

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Student student = context.getBean("student", Student.class);
    System.out.println(student);
    /**
     * Student{name='syg',
     *  address=Address{address='罗德岛'},
     *  books=[红楼梦, 西游记, 水浒传, 三国演义],
     *  hobbies=[乒乓球, 听歌, 看电影],
     *  card={身份证=112332231, 银行卡=2132132312},
     *  games=[崩坏3, 穿越火线],
     *  info={学号=2017100, 性别=男, 昵称=香榭的落叶},
     *  wife='null'}
     * */
}

构造器注入

同上述。

拓展方法注入

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

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--p命名空间注入,可以直接注入属性值-->
    <bean id="user" class="com.pojo.User" p:name="syg" p:age="21"/>
    <!--c命名空间注入,通过构造器注入-->
    <bean id="user2" class="com.pojo.User" c:age="21" c:name="syg"/>
</beans>
public void test() {
    ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
    System.out.println(context.getBean("user", User.class));
}

注意需要添加的两个约束
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"

Bean作用域

scope属性

  • singleton: 默认值,单例的,可以显示设置

    <bean id="user2" class="com.pojo.User" c:age="21" c:name="syg" scope="singleton"/>

  • prototype: 原型,多例的.

    <bean id="user2" class="com.pojo.User" c:age="21" c:name="syg" scope="prototype"/>

  • request: WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中.

  • session: WEB项目中,Spring创建一个Bean的对象,将对象存入到session域中.

  • globalSession : WEB 项目中,应用在Porlet环境。如果没有Porlet 环境那么globalSession相当与session

Bean自动装配

  • 自动装配是Spring满足Bean依赖的一种方式
  • Spring会在上下文中自动寻找,自动给Bean装配属性

在Spring中有三种装配方式

  1. xml中显示配置
  2. java中显示配置
  3. 隐式自动装配bean

byName装配

<bean id="cat" class="com.pojo.Cat"/>
<bean id="dog" class="com.pojo.Dog"/>
<bean id="person" class="com.pojo.Person" autowire="byName">
    <property name="name" value="syg"/>
</bean>

byName

在容器上下文中查找和对象set方法签名后的值(比如setDog,set为后dog,需要找到iddog的bean完成自动装配)

set方法要符合驼峰命名格式,查找dog是小写,不识别大写。

byType装配

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

通过对象属性类型查找bean。被查找的bean可以不需要id。

但是byType需要保证上下文中同类型只有一个bean,不然报错不能识别

注解装配

注解xml配置

  1. 导入约束 /context
  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:component-scan base-package="com"/>
    <!--开启component-scan可以不用开启annotation-config因为前者包含了后者-->
    <context:annotation-config/>
</beans>

@Autowired使用

//autowired可以设置required = false,即可设置为空
public @interface Autowired {
    boolean required() default true;
}
@Autowired
Dog
@Autowired(required = false)
@Qualifier(value = "dog")
public void setDog(Dog){}

可以在属性上使用,在属性上使用可以不需要set方法。

可以在set方法上使用。

如果bean注册了多个,可通过@Qualifier设置value为bean id区分

@Resource使用

@Resource(name = "cat")
private Cat cat;

@Resource(type = Cat.class)
private Cat cat;

name指定bean id,查找到对应的bean注入,若未指定id,且同类型的bean不唯一,会报错。

type指定bean类型,设置代表通过类型查找。

Resource和Autowired

都可以用来属性装配,都可以放在属性上。

@Autowired使用byType方式查找。

@Resource默认使用byName查找,如果找不到名字,通过byType。

注解开发

使用注解开发必须保证aop的包导入了。

并且导入约束,添加xml配置。

@Component
@Scope("singleton")
public class User {
    @Value("syg")
    public String name;
    @Value("syg1")
    public void setName(String name) {
        this.name = name;
    }
}

@Component

设置类被spring托管为Bean对象。

@Scope

public @interface Scope {
    
   @AliasFor("scopeName")
   String value() default "";

   @AliasFor("value")
   String scopeName() default "";
    
   ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}

通过scope注解设置单例,等模式

@Value

属性上添加注解,为属性赋值。相当于xml中的property赋值

可以放在属性或者set方法上,若两个都存在,值为set方法上注解的赋值。

@Repository,@Service,@Controller

这三个都是component衍生注解,分别对应mvc三层的而细分

xml更加通用,方便维护。

注解不能引用其他bean,维护相对复杂。

实践:xml负责管理bean,注解负责属性注入。

自动装配注解在上面

Java 配置类配置

JavaConfig是Spring的一个子项目,在Spring4之后成为了核心功能。

/**
 * Describe:
 * Configuration 也是个Spring组件,注册在Spring容器中的一个@Component
 * 它能代替beans.xml配置文件的作用
 */
@Configuration
//配置注解扫描
@ComponentScan("com.pojo")
//导入其他配置类
@Import({MyConfig2.class})
public class MyConfig {
    /**
     * 注册一个Bean,相当于xml中写的bean标签
     * 方法的签名可以看做bean标签的id
     * 方法返回值类型相当于bean标签的class
     */
    @Bean
    public User getUser() {
        return new User();
    }
}

使用配置类,需要用配置类的上下文实现类,使用配置类的class对象加载

这里在getBean的时候可通过方法名,也可以通过类的小写获取,因为Spring在把Bean放入容器的时候默认id为类名小写

@Test
public void name() {
    ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
    System.out.println(context.getBean("getUser"));//或getBean("user")
}

代理模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DpI4F9sP-1593686235332)(Spring框架.assets/image-20200701171723025.png)]

静态代理

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

代理模式好处

  • 真实角色操作更单一,不用关注公共业务。
  • 公共业务交给代理角色,实现业务分工
  • 公共业务发生扩展的时候方便管理

缺点

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

测试类

租房,抽象角色

public interface Rent {
    void rent();
}

房东,真实角色

public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

中介,代理角色

public class Proxy implements Rent {
    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        viewHouse();
        host.rent();
        contract();
        fare();
    }

    /**
     * 看房
     */
    private void viewHouse() {
        System.out.println("中介带你看房");
    }

    /**
     * 租赁合同
     */
    private void contract() {
        System.out.println("签租赁合同");
    }

    /**
     * 收中介费
     */
    private void fare() {
        System.out.println("收中介费");
    }
}

测试

@Test
public void name() {
    Host host = new Host();
    //中介(代理)帮房东租房
    Proxy proxy = new Proxy(host);
    //中介(代理)一般会做附属操作
    proxy.rent();
}

动态代理

  • 角色和静态代理一样
  • 动态代理类是动态生成的

基于接口的动态代理

两个类:Proxy,Invokca tionHandler

代理处理类

public class ProxyHandler implements InvocationHandler {
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    /**
     * 生成代理对象
     */
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this);
    }

    /**
     * 处理代理实例,并返回结果
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        //动态代理的本质:使用反射
        return method.invoke(target, args);
    }
    private void log(String msg){
        System.out.println("执行了" + msg + "方法");
    }
}

测试

public static void main(String[] args) {
    //真实角色
    Rent host = new Host();
    //代理处理类
    ProxyHandler ph = new ProxyHandler();
    //设置被代理的接口实现类
    ph.setTarget(host);
    //动态生成代理类
    Rent rent = (Rent) ph.getProxy();
    rent.rent();

}

动态代理好处

  • 真实角色操作更纯粹
  • 公共业务给代理类角色,实现业务分工
  • 业务扩展时方便管理
  • 动态代理的是接口,代表了一类业务
  • 一个动态代理可代理多个类,只要是实现相应接口的类

其他方式

jdk动态代理

基于类的动态代理cglib,java字节码动态代理javasist

AOP

什么是AOP

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

  • AspectJ是一个面向切 面的框架, 它扩展了Java诸言。 AspectJ定义了AOP语法所以它有一个专I门的编译器用来生成遵守Java字节编码规范的Class文件。
  • Aspect是一个基于Java语言的AOP框架
  • Spring2.0以后新增了对Aspect切点表达式支持
  • @AspectJ是AspectU1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面

AOP在Spring中的作用

提供声明式事务,允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部
    分,就是横切关注点。如日志,安全,缓存,事务等等…
  • 切面(ASPECT) :横切关注点被模块化的特殊对象。即,它是一个类。
  • 通知(Advice) :切面必须要完成的工作。即,它是类中的一一个方法。
  • 目标(Target) :被通知对象。
  • 代理(Proxy) :向目标对象应用通知之后创建的对象。
  • 切入点(PointCut) :切面通知执行的“地点”的定义。
  • 连接点(ointPoint) :与切入点匹配的执行点。

SpringAOP中通过Advice定义横切逻辑,Spring中支持五种类型的Advice

通知类型连接点实现接口
前置通知方法方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环绕通知方法前后org.aopalliance.intercept.MethodInterceptor
异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdvice
引介通知类中增加新的方法属性org.springframework .aop.IntroductionInterceptor

xml使用AOP

导入依赖

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

方式1:通过实现通知接口

<!--注册业务类0-->
<bean id="userService" class="com.syg.service.UserServiceImpl"/>
<!--注册实现通知接口的切入点类-->
<bean id="log" class="com.syg.log.Log"/>
<bean id="afterLog" class="com.syg.log.AfterLog"/>
<!--需要导入aop约束-->
<aop:config>
    <!--切入点,expression表达式,execution(要执行的位置)-->
    <aop:pointcut id="pointcut" expression="execution(* com.syg.service.UserServiceImpl.*(..))"/>
    <!--执行环绕增强-->
    <aop:advisor advice-ref="log" pointcut-ref ="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref ="pointcut"/>
</aop:config>

编写业务类

编写实现横切功能的类,并实现上述相应通知的接口

在xml文件中注册bean,并配置业务类需要切入的功能函数,设置通知方式。

execution表达式

execution(访问限定符 返回类型 类名(这里为全路径名).方法名(参数列表))
参数列表:(…)可以代表所有参数,()代表一个参数,(,String)代表第一个参数为任何值,第二个参数为String类型.

方式2:自定义切面,xml配置aop

<!--自定义切面类,包含通知的方法-->
<bean id="diy" class="com.syg.diy.DiyPointCut"/>
<aop:config>
    <!--自定义切面,ref:引用自定义切面类-->
    <aop:aspect ref="diy">
        <!--切入点-->
        <aop:pointcut id="point" expression="execution(* com.syg.service.UserServiceImpl.*(..))"/>
        <!--通知,将切面类的方法应用到切入点-->
        <aop:before method="before" pointcut-ref="point"/>
        <aop:after method="after" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>

注解使用AOP

编写切面类,里面包含通知方法

@Aspect
public class AnnoPointCut {
    @Before("execution(* com.syg.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("方法执行前");
    }

    @After("execution(* com.syg.service.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("方法执行后");
    }

    @Around("execution(* com.syg.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前知");
        //被执行的方法的签名
        System.out.println(jp.getSignature());
        jp.proceed();
        System.out.println("环绕后");
    }
}

xml中注册bean,并配置aop的代理

<bean id="anno" class="com.syg.diy.AnnoPointCut"/>
<!--开启注解支持,Spring默认的动态代理实现为JDK(proxy-target-class="false"),设置为true使用cglib-->
<aop:aspectj-autoproxy proxy-target-class="false"/>

整合Mybatis

  • 导入依赖

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.5.RELEASE</version>
    </dependency>
    
    <!--spring连接数据库需要spring-jdbc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.7.4</version>
    </dependency>
    
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.4</version>
    </dependency>
    

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>
    <typeAliases>
        <package name="com.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!--jdbc的事务管理-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver"
                          value="com.mysql.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username"
                          value="root"/>
                <property name="password"
                          value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <!--    每一个Mapper.xml都需要mybatis中注册-->
    <mappers>
        <mapper class="com.mapper.UserMapper"/>
    </mappers>
</configuration>

编写实体类,编写接口

编写mapper.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">
<!--namespace绑定一个Dao/Mapper接口-->
<mapper namespace="com.mapper.UserMapper">
    <!--    id对应Dao接口方法名-->
    <select id="selectUser" resultType="User">
        select * from mybatis.user
    </select>
</mapper>

Mybatis-Spring

  1. 编写数据源配置
  2. sqlSessionFactory
  3. SqlSessionTemplate
  4. 编写接口的实现类

Spring上下文中的数据源配置

<!--使用Spring数据源替换mybatis配置
    这里使用spring提供的jdbc,数据源-->
<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?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="1234"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--绑定mybatis配置文件-->
    <property name="configLocation" value="mybatis-config.xml"/>
    <property name="mapperLocations" value="com/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate 即为使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--只能使用构造器注入,因为SqlSessionTemplate没有set方法-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

业务接口

public interface UserMapper {
    List<User> selectUser();
    int addUser(User user);
    int delUser(int id);
    int updUser(User user);
}

业务类

@Component(value = "userMapper")
public class UserMapperImpl implements UserMapper {
    @Autowired
    private SqlSessionTemplate sqlSession;

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

测试

@Test
public void name() throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
    System.out.println(userMapper.selectUser());
}

Spring事务管理

事务概念:一组操作,所有成功则成功,有一个失败则失败

事务特性:原子性,一致性,隔离性,持久性

  • 声明式事务: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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <!--使用Spring数据源替换mybatis配置
        这里使用spring提供的jdbc,数据源-->
    <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?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>
    
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis配置文件-->
        <property name="configLocation" value="mybatis-config.xml"/>
        <property name="mapperLocations" value="com/mapper/*.xml"/>
    </bean>
    
    <!--SqlSessionTemplate 即为使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入,因为SqlSessionTemplate没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    
    <!--配置声明式事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>

    </bean>

    <!--结合AOP进行事务织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务传播特性:propagation默认REQUIRED-->
        <tx:attributes>
            <tx:method name="sel*" propagation="REQUIRED"/>
            <tx:method name="delete"/>
            <tx:method name="query"/>
        </tx:attributes>
    </tx:advice>

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

注意 tx:method 的 name 属性是匹配切面类里的方法名称

这样执行切面类的方法就会增加事务支持,当方法内出现错误异常时会回滚所有的操作。

为什么需要事务

  • 为了保持数据的一致性

声明式事务(注解)

配置事务管理器

和上述一样

<!--配置声明式事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>

配置事务注解驱动

<!--注解驱动,transaction-manager属性可以省略-->
<tx:annotation-driven transaction-manager="transactionManager"/>

事务方法所在的类上添加注解

@Service(value = "userMapper")
@Transactional
public class UserMapperImpl implements UserMapper {
    @Autowired
    private SqlSessionTemplate sqlSession;

    public List<User> selectUser() {
        addUser(new User(5, "syg", "ppp"));
        delUser(5);
        return sqlSession.getMapper(UserMapper.class).selectUser();
    }

    public int addUser(User user) {
        return sqlSession.getMapper(UserMapper.class).addUser(user);
    }

    public int delUser(int id) {
        return sqlSession.getMapper(UserMapper.class).delUser(id);
    }

    public int updUser(User user) {
        return 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
毕业设计,基于SpringBoot+Vue+MySQL开发的公寓报修管理系统,源码+数据库+毕业论文+视频演示 现代经济快节奏发展以及不断完善升级的信息化技术,让传统数据信息的管理升级为软件存储,归纳,集中处理数据信息的管理方式。本公寓报修管理系统就是在这样的大环境下诞生,其可以帮助管理者在短时间内处理完毕庞大的数据信息,使用这种软件工具可以帮助管理人员提高事务处理效率,达到事半功倍的效果。此公寓报修管理系统利用当下成熟完善的Spring Boot框架,使用跨平台的可开发大型商业网站的Java语言,以及最受欢迎的RDBMS应用软件之一的MySQL数据库进行程序开发。公寓报修管理系统有管理员,住户,维修人员。管理员可以管理住户信息和维修人员信息,可以审核维修人员的请假信息,住户可以申请维修,可以对维修结果评价,维修人员负责住户提交的维修信息,也可以请假。公寓报修管理系统的开发根据操作人员需要设计的界面简洁美观,在功能模块布局上跟同类型网站保持一致,程序在实现基本要求功能时,也为数据信息面临的安全问题提供了一些实用的解决方案。可以说该程序在帮助管理者高效率地处理工作事务的同时,也实现了数据信息的整体化,规范化与自动化。 关键词:公寓报修管理系统;Spring Boot框架;MySQL;自动化;VUE
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值