spring笔记

Spring

1.简介

  • 使现有的技术更加容易使用,本身是一个大杂烩,整合了现在的技术框架

官网:https://spring.io/projects/spring-framework#overview

GitHub:https://github.com/spring-projects/spring-framework

Maven:

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

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

2.优点:

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

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

3.组成

4.拓展

现代化的java开发!基于Spring的开发

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

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

一、IOC理论推导

二、HelloSpring

1.编写实体类

2.编写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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring创建对象,在spring中这些都称为bean-->
<!--
    id = 对象名
    class = new 的对象
    property 相对于给对象中的属性赋值
        name = 属性名
        value = 属性值
        ref = 引用类型的值
-->
    <bean id="hello" class="com.study.pojo.Hello">
        <property name="str" value="Spring你好"/>
    </bean>

</beans>

3.测试运行

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());

三、IOC创建对象的方式

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

  2. 假设使用有参构造创建对象

    1. 下标赋值
    <bean id="hello" class="com.study.pojo.Hello">
        <constructor-arg index="0" value="少文"/>
    </bean>
    
    1. 通过类型(不建议使用)多个参数类型一样时候,就不适用了
    <bean id="hello" class="com.study.pojo.Hello">
        <constructor-arg type="java.lang.String" value="少文"/>
    </bean>
    
    1. 直接通过参数名(建议使用)
    <bean id="hello" class="com.study.pojo.Hello">
        <constructor-arg name="str" value="少文"/>
    </bean>
    

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

四、Spring配置

1.别名alias

<alias name="hello" alias="hi"/>

2.Bean的配置

  • id:bean的唯一标识符,相对于我们学的对象名
  • class:bean对象所对应的全限定名:包名+类名
  • name:也是别名,可以起多个别名 可以用"," " " ";" 隔开

3.import

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

applicationContext.xml

<import resource="beans2.xml"/>
<import resource="beans.xml"/>

这样直接使用总的配置就可以。

五、DI依赖注入

1.构造器注入

前面已经说过了

2.Set方式注入【重点】

  • 依赖注入:set注入
  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象中所有的属性,由容器来注入
    <bean id="address" class="com.study.pojo.Address">
        <property name="address" value="山西省"/>
    </bean>

    <bean id="student" class="com.study.pojo.Student">
<!--        普通类型-->
        <property name="name" value="小张"/>
<!--        引用类型-->
        <property name="address" ref="address"/>
<!--        数组类型-->
        <property name="book">
            <array>
                <value>西游记</value>
                <value>水浒传</value>
                <value>红楼梦</value>
            </array>
        </property>
<!--        List-->
        <property name="hobby">
            <list>
                <value>打代码</value>
                <value>读书</value>
            </list>
        </property>
<!--        Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>LOL</value>
                <value>BOB</value>
                <value>COC</value>
            </set>
        </property>
<!--        Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="11111111111111111"/>
                <entry key="银行卡" value="888888888888"/>
            </map>
        </property>
<!--        null-->
        <property name="wife">
            <null></null>
        </property>
<!--        Properties-->
        <property name="info">
            <props>
                <prop key="学号">2009312146</prop>
                <prop key="班级">计算机2001</prop>
                <prop key="年级">大四</prop>
            </props>
        </property>
    </bean>

3.拓展方式注入

  • P命名空间
  • C命名空间

1.导入xml约束

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

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

2.编写xml

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

<bean id="user1" class="com.study.pojo.User" c:age="20" c:name="小李"/>

4.Bean作用域

1.单例模式【默认的】 singleton

​ 显示定义

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

2.原型模式(prototype) 每次从容器中get,都会产生一个新的对象

<bean id="user" class="com.study.pojo.User" p:age="18" p:name="小张" scope="prototype"/>

六、Bean的自动装配

1.ByName

<bean id="cat" class="com.study.pojo.Cat"/>
<bean id="dog" class="com.study.pojo.Dog"/>

<bean id="people" class="com.study.pojo.People" autowire="byName">
    <property name="name" value="小张"/>
</bean>
  • 在容器上下文中查找,和自己对象set方法后面的值对应的 bean的id

2.ByType

<bean class="com.study.pojo.Cat"/>
<bean class="com.study.pojo.Dog"/>

<bean id="people" class="com.study.pojo.People" autowire="byType">
    <property name="name" value="小张"/>
</bean>
  • 在容器上下文中查找,和自己对象属性类型相同的bean

3.注解实现自动装配

使用注解须知:

1.导入约束

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

http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<?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/>

2.配置注解的支持

<!--开启注解支持-->
<context:annotation-config/>

@Autowired 和 @Qualifer【常用】

@Autowired
@Qualifier(value = "cat11")
private Cat cat;

@Autowired
private Dog dog;
  • 直接在实体类属性上注解
  • 查找顺序,先按类型,再按名字
  • @Qualifer(value = “ ”) 可以直接指定ByName进行匹配 与Autowired配套使用

@Resource

1.导入jar包

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>
@Resource
private Cat cat;

@Resource(name = "dog11")
private Dog dog;

小结

@Resource与@Autowire的区别:

  • 都是自动装配的,都可以放在属性字段上
  • @Resource 默认通过byname实现,找不到,则通过byType
  • @Autowire默认通过bytype实现,找不到,则通过byname

七、使用注解开发

  • spring4之后,使用注解开发,需要保证aop包导入

  • 使用注解开发需要保证context约束,增加注解支持

1.bean

@Component:组件放在类上,说明这个类被Spring管理,就是Bean

@Component
public class User {

2.属性如何注入

@Value 

@Component
public class User {

    @Value("小张")
    private String name;

3.衍生的注解

  • @Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层
    • dao 【@Repository】
    • service 【@Service】
    • controller 【@Controller】
  • 这四个功能都是一样的,都是代表某个类注册到Spring中装配Bean

4.自动装配置

  • @Autowired
  • @Qualifei
  • Resource

5.作用域

  • @Scope
@Component
@Scope(value = "prototype")
public class User {

    @Value("小张")
    private String name;

6.小结

​ xml与注解

  • xml更加万能,适用于任何场合,维护方便简单!

  • 注解:不是自己的类是用不了,维护相对复杂!

    xml与注解最佳实践

  • xml用来管理bean

  • 注解只负责完成属性的注入

  • 我们在使用过程中,只需要注意一个问题,必须让注解生效,开启注解支持

八、使用java的方式配置Spring

1.编写实体类

  • 注入值
@Component
public class User {
    @Value("小张")
    private String name;

    @Override
    public String toString() {
        return "User{" +
                "name=&#39;" + name + &#39;&#39;&#39; +
                &#39;}&#39;;
    }

    public String getName() {
        return name;
    }

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

2.编写配置类

  • @Configuration,会注册到容器中,有误他本身就是一个@Component

  • @Configuration 代表这是一个配置类,等价于之前的 beans.xml

  • @bean 注册一个bean,相对于之前的Bean标签

  • 方法名 相对于标签中的 id

  • 返回值 相对于标签中的class

@Configuration
@ComponentScan("com.study.pojo")
@Import(StudyConfig2.class)
public class StudyConfig {

    @Bean
    public User user(){
        return new User();
    }
}

3.测试

  • 注解方式使用 new AnnotationConfigApplicationContext(StudyConfig.class);
public static void main(String[] args) {

    ApplicationContext context = new AnnotationConfigApplicationContext(StudyConfig.class);	
    User user = context.getBean("user", User.class);
    System.out.println(user.getName());

}

九、代理模式

  • SpringAOP的底层!
  • 代理模式分类:
    • 静态代理
    • 动态代理

1.静态代理

  • 抽象角色(租房这个事情):一般使用接口或者抽象类解决
  • 真实角色(租房的人):被代理的角色
  • 代理角色(中介):代理真实角色,代理真实角色后,我们一般会做一些附属操作
  • 客户:访问代理的人

代理模式好处:

  • 可以使真实的角色更加纯粹!不用关心一些公共的业务
  • 公共也就交给代理角色!实现了业务的分工
  • 公共业务发送扩展的时候,方便集中管理

缺点:

  • 一个真实角色就会产生一个代理角色;代码量会翻倍 效率变低

2.动态代理

  • 动态代理和静态代理角色一样
  • 动态代理代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口 JDK动态代理
    • 基于类 cglib
    • java字节码实现 javasist

需要了解两个类:Proxy:代理,invocationHandler:调用处理程序

1.创建代理处理程序

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyInvocationHandler 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 {
        seeHost();
        Object result = method.invoke(target, args);
        contract();
        return result;
    }

    //    看房
    public void seeHost(){
        System.out.println("带客户看房");
    }
    //    签租赁合同
    public void contract(){
        System.out.println("签租赁合同");
    }
}

提取为工具类:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyInvocationHandler 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 {
        Object result = method.invoke(target, args);
        return result;
    }
}

2.调用过程

public static void main(String[] args) {
    //真实对象
    HostBoss hostBoss = new HostBoss();
    //代理对象 通过动态获得
    ProxyInvocationHandler pih = new ProxyInvocationHandler();
    //需要代理的对象
    pih.setTarget(hostBoss);
    //得到代理对象
    Rent proxy = (Rent) pih.getProxy();
    proxy.rent();
}

十、AOP

3.使用spring实现Aop

方式一:原生的Spring API 接口

  1. 导入jar包
<!--        Aop织入-->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

2.编写日志

import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {

    @Override
    public void afterReturning(Object o, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("after"+target.getClass().getName()+"-->"+method.getName());
    }
}
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class BeforeLog implements MethodBeforeAdvice {

    //method 要执行的目标对象的方法
    //args 参数
    //target 目标对象
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("before执行了"+target.getClass().getName()+"-->"+method.getName());
    }
}

3.真实的对象(需要被代理的对象)

public class UserServiceImpl implements UserService{
    @Override
    public void add() {
        System.out.println("add一个用户");
    }

    @Override
    public void delete() {
        System.out.println("delete一个用户");
    }

    @Override
    public void update() {
        System.out.println("update一个用户");
    }

    @Override
    public void query() {
        System.out.println("query一个用户");
    }
}

4.编写配置文件(最重要的一步)

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="com.study.service.UserServiceImpl"/>
    <bean id="afterLog" class="com.study.log.AfterLog"/>
    <bean id="beforeLog" class="com.study.log.BeforeLog"/>

<!--    配置aop 需要导入约束-->
    <aop:config>
<!--        切入点     execution(修饰符 返回值 类名 方法名 参数)-->
        <aop:pointcut id="pointcut" expression="execution(* com.study.service.UserServiceImpl.*(..))"/>
<!--        执行环绕增加-->
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

5.测试

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

        UserService userService = (UserService) context.getBean("userService");
        userService.delete();
    }

方式二:自定义来实现AOP

1.编写切面

public class DiyPointCut {
    public void before(){
        System.out.println("=======方法执行前=========");
    }
    public void after(){
        System.out.println("=======方法执行后=========");
    }
}

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"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="com.study.service.UserServiceImpl"/>
    <bean id="diy" class="com.study.diy.DiyPointCut"/>

    <aop:config>
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="pointcut" expression="execution(* com.study.service.UserServiceImpl.*(..))"/>
<!--            通知-->
            <aop:after method="after" pointcut-ref="pointcut"/>
            <aop:before method="before" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解实现

1.编写切面类

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

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

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

    @Around("execution(* com.study.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("环绕前");
        pj.proceed();
        System.out.println("环绕后");
    }

    @AfterReturning("execution(* com.study.service.UserServiceImpl.*(..))")
    public void AfterReturning(){
        System.out.println("AfterReturning执行");
    }

}

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"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="com.study.service.UserServiceImpl"/>
    <bean id="annotation" class="com.study.diy.AnnotationPointCut"/>
<!--    开启注解支持-->
    <aop:aspectj-autoproxy/>

3.测试

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

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

        UserService userService = (UserService) context.getBean("userService");
        userService.delete();
    }
}

  • 坏绕前-->befor-->目标方法执行-->环绕后-->after

十一、整合Mybatis

1.导入jar包

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <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.2</version>
        </dependency>
<!--        spring操作数据库需要 spring-jdbc的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.9</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.2</version>
        </dependency>

    </dependencies>
  • Mybatis-Spring 版本的选择

1.编写数据源配置

<!--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;amp;characterEncoding=utf8&amp;amp;useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

2.sqlSessionFactory

<!--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/study/mapper/*.xml"/>
    </bean>

3.sqlSessionTemplate

<!--sqlSessionTemplate:就是我们使用的SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        因为没有set方法只能使用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

4.给接口添加实现类

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

import java.util.List;

public class UserMapperImpl implements UserMapper{

    SqlSessionTemplate sqlSession;

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

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

5.实现类配置到spring中

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

6.测试

public void getUser(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapperImpl = context.getBean("userMapperImpl", UserMapper.class);
    List<User> userList = userMapperImpl.getUser();
    for (User user : userList) {
        System.out.println(user);
    }
}

spring-dao.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">
<!--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;amp;characterEncoding=utf8&amp;amp;useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </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/study/mapper/*.xml"/>
    </bean>
<!--sqlSessionTemplate:就是我们使用的SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        因为没有set方法只能使用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

第二种实现接口的方式:

import com.study.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> getUser() {
        return getSqlSession().getMapper(UserMapper.class).getUser();
    }
}
<bean id="userMapperImpl2" class="com.study.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

十二、声明式事务

1.事务

  • 要么都成功,要么都失败
  • 在项目开发中十分重要,涉及到数据的一致性
  • 确保完整性和一致性

事务的ACID原则

  • 原子性

  • 一致性

  • 隔离性

  • 持久性

2.spring的事务管理

  • 声明式事务:AOP
  • 编程式事务:

主要就是配置配置文件

<!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--给哪些方法配置事务-->
    <!--propagation 配置事务的传播特性-->
        <tx:attributes>
            <tx:method name="addUser" propagation="REQUIRED"/>
            <tx:method name="delUser"/>
            <tx:method name="updateUser"/>
            <tx:method name="queryUser"/>
            <tx:method name="getUser"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
<!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.study.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
原文地址:https://www.cnblogs.com/20183544-wangzhengshuai/p/15235582.html