Spring 学习

基本概念:

  Spring是一种轻量级控制反转(IOC)和 面向切面(AOP)的容器框架。

 

IOC(控制反转)理论:

  

  控制反转是一种涉及思想,DI(依赖注入)是实现Ioc的一种方法。


  控制反转是一种通过描述(xml或者注解)并通过第三方生产或获取特定对象的方式。再Spring 中实现控制反转的是IOC 容器,其实现方法是依赖注入。

 

IOC创建对象(步骤):

 

1、构造器注入:

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

  3、获取spring 上下文对象 

public class MyTest {
    public static void main(String[] args) {
        //获取spring上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //所有对象都在spring中管理了,使用直接取出即可。
        //方式1: 通过beans.xml 文件中 id 获取
        Hello bean = (Hello) context.getBean("hello");

        //方式2 : 直接通过class 获取
        Hello bean1 = context.getBean(Hello.class);
        System.out.println(bean.toString());
    }
}

 注意:默认使用无参构造。

 

有参构造:

  1、使用下标赋值:

<bean id="hello2" class="com.chuxin.pojo.Hello">
			
  <!--以构造参数顺序从 '0' 开始 -->
  <constructor-arg index="0" value="lisi"/>
				
</bean>

  2、通过类型赋值(不建议使用)

<!--方法2:通过类型 赋值 -->
<bean id="hello" class="com.chuxin.pojo.Hello">
			
  <!--根据构造参数类型赋值-->
  <constructor-arg type="java.lang.String" value="list"/>
				
</bean>

  3、通过参数名称赋值

<bean id="hello" class="com.chuxin.pojo.Hello">
       
  <!--参数名称赋值-->
  <constructor-arg name="name" value="lishi"/>
  
</bean>

备注:<import>标签: 可以将多个xml 文件导入成一个 ,之后创建只需创建总的 xml 即可。一般用 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="beans.xml"/>
</beans>

  

2、依赖注入:

  依赖:bean 对象的创建依赖于容器。

  注入:bean对象中的属性由容器注入。

3、Set方式注入:

  代码示例: 示例中粘贴均 省略了 get、set、toString 方法,实际情况 需要加上。

  Student类:

public class Student {

    private String name;

    private Address address;

    private String[] book;

    private List<String> hobbys;

    private Map<String, String> card;

    private Set<String> games;

    private Properties info;

    private String wife;

    /// 省略了get 、set 、toString 方法
    
}

  User类:

public class User {

    private String name;

    private int age;
    
}

  Address 类:

public class Address {

    private String address;

}

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

    <bean id="address" class="com.chuxin.pojo.Address">
        <property name="address" value="山东省"/>
    </bean>

    <bean id="student" class="com.chuxin.pojo.Student">
        <!--1、普通值注入-->
        <property name="name" value="张三"/>
        <!--2、bean注入,ref-->
        <property name="address" ref="address"/>
        <!--3、数组注入-->
        <property name="book">
            <array>
                <value>张三</value>
                <value>李四</value>
                <value>王五</value>
                <value>赵六</value>
            </array>
        </property>
        <!--4、list数组 注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>看电影</value>
                <value>画画</value>
            </list>
        </property>

        <!--5、map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="1234567890"/>
                <entry key="银行卡" value="1234567890"/>
            </map>
        </property>
        <property name="games">
            <set>
                <value>LOL</value>
                <value>DNF</value>
            </set>
        </property>
        <!--6、null 值 注入-->
        <property name="wife">
            <null/>
        </property>
        <!--7、properties 配置类注入-->
        <property name="info">
            <props>
                <prop key="number">1241231</prop>
                <prop key="name">小明</prop>
                <prop key="sex">男</prop>
            </props>
        </property>
    </bean>
</beans>

4、拓展方式注入:

  P标签命名空间注入(get、set 注入):

    须在 beans标签中加入  : xmlns:p="http://www.springframework.org/schema/p"

     c标签命名空间注入(构造器 注入):

    须在 beans 标签中加入 :   xmlns:c="http://www.springframework.org/schema/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命名空间注入: 通过 get set 注入-->
    <bean id="user" class="com.chuxin.pojo.User" p:age="18" p:name="张三"/>

    <!--c标签命名空间注入: 通过构造器注入-->
    <bean id="user2" class="com.chuxin.pojo.User" c:name="张三" c:age="18"/>
  
</beans>

bean的作用域:

 bean 模式:

  单例模式: 须在bean 标签中 加入 scope 属性 并选中 singleton 单例。 Spring 默认为 单例模式。

       <!--单例模式-->
       <bean id="user2" class="com.chuxin.pojo.User" c:name="张三" p:age="18" scope="singleton"/>

  原型模式: bean标签中 加入 scope 属性并选中 prototype ,则每次调用都会重新构建对象。

       <!--原型模式-->
       <bean id="user3" class="com.chuxin.pojo.User" c:name="张三" p:age="18" scope="prototype"/>

  其余的request、session、application 、这些只能再web 开发中使用。

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


    <!--c标签命名空间注入: 通过构造器注入-->
    <!--单例模式-->
    <bean id="user2" class="com.chuxin.pojo.User" c:name="张三" c:age="18" scope="singleton"/>
    <!--原型模式-->
    <bean id="user3" class="com.chuxin.pojo.User" c:name="张三" c:age="18" scope="prototype"/>


</beans>

bean自动装配:

 自动装配是Spring 满足bean 依赖的一种。Spring 会上下文寻找,并给bean 自动装配。

  

 spring 中三种装配方式:

   1、再xml中显示配置。

   2、再java 显示配置。

   3、隐式的自动装配bean。

 byName:会自动在容器上下文寻找,和自己对象set 方法后面的值对应的bean id。

<!-- byName: 会自动在容器上下文寻找,和自己对象set 方法后面的值对应的bean id -->
<bean id="people" class="com.chuxin.pojo.People" autowire="byName">
  <property name="name" value="张三"/>
</bean>

 注意:byName 需要保证所有bean的id 唯一,并且这个bean 需要和自动注入的属性set 方法的值一样。

 

 byType:会自动再容器上下文寻找,和自己对象属性类型相同的bean

<!--byType : 会自动再容器上下文寻找,和自己对象属性类型相同的bean-->
<bean id="people2" class="com.chuxin.pojo.People" autowire="byType">
  <property name="name" value="张三"/>
</bean>

 注意:需要保证bean的Class唯一,并且这个bean 需要和自动注入的属性类型一致。

 

 使用注解自动装配:

   使用注解方式:

    1、导入约束 : contex 约束。

    2、配置注解支持 : <context:annotation-config/> (必须有)

须在 beans 标签中 加入  :
				  
<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(required = true) :  不写默认 required  默认为true,不允许为空。 如果 为false 表示这个对象可以为null 在属性上使用。也可以在set 方式上使用。


使用Autowired 我们可以不用编写Set方法,前提这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName

  @Nullable: 字段标记此注解,说明这个字段可以为null。

  @Qualifier: 可以指定唯一对象

  如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】实现时、可以配合@Qualifier(value = "bean的id")配合使用,指定一个唯一的bean。

        

  @Resource 注解

   如果自动装配中bean的id 和类型 都不存在 则会报错,反之 先去寻找bean的id ,如果匹配不到,再去匹配bean 类型。

 

小结:

  @Autowired 和 @Resource 的区别:

    1、都是用来自动装配的,都可以放在属性字段上。

    2、@Autowired 通过byName来实现,必须要求这个对象存在。{常用}

    3、@Resource 默认通过byName实现,如果找不到名字,则通过byType实现,如果两个都找不到就抛出异常。

    4、执行顺序不同:@Autowired通过byType的方式实现。 @Resource通过byName的方式实现。

注解使用:

  

  @Component: 放在类上 等价于<bean id="user" class="com.chuxin.pojo.User"></bean>。

  衍生注解:

    dao : @Repository

    service : @Service

    controller : @controller

小结: 这4个注解功能都是一样的都是将某个类注册到Spring 容器中,装配bean

  @Value: 放在属性上使用 等价于 <bean id="user2" class="com.chuxin.pojo.User"><property name="name" value="张三"/></bean>

  @Scope: 作用域注解。

 

使用java 的方式配置spring:

  1、自定义配置类: 需在 类上 使用@Configuration 注解 ,如果完全使用 如果完全使用配置类方式去做,只能通过AnnotationConfigApplicationContext 上下文获取容器,通过容器获取对象

配置类:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/28 01:07
 */
// 这个注解被spring 容器托管,注册到容器中,应为他本来就是一个@Component,@Configuration 代表时一个配置类,就和我们beans.xml一样
// 如果定义 此类为配置类 则它可以 做 xml 中的 操作 例如: 开启扫描。
@Configuration
public class Myconfig {

    /**
     *  注册一个bean,相当于写了一个bean 标签
     *  方法名相当于 bean 的 id
     *   返回值相当于bean 标签中的class 属性
     * @return
     */
    @Bean
    public User getUser() {
        // 返回要注入的对象
        return new User();
    }
}

实体类:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/28 01:07
 */
//这里这个注解意思就是 这个类被Spring 接管注册到了容器中
@Component
public class User {

    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

测试类:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/28 01:09
 */
public class MyTest {
    public static void main(String[] args) {
        //如果完全使用配置类方式去做,只能通过AnnotationConfigApplicationContext 上下文获取容器,通过容器获取对象。
        ApplicationContext context = new AnnotationConfigApplicationContext(Myconfig.class);
        User getUser = context.getBean("getUser", User.class);
        System.out.println(getUser);
    }
}

  22:28:08

Aop 概念:

 

  aop是 面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。

 

AOP再Spring 中的作用:

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

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

  2、切面(Aspect): 横切关注点 被模块化 的特殊对象。

  3、通知(Advice):切面必须要完成的工作。

  4、目标(Target):被通知的对象

  5、代理(Proxy):向目标对象应用通知后创建对象。

  6、切入点(PointCut): 切面通知 执行的“地点”的定义i。

  7、连接点(JointPoint):与切入点匹配的执行点。

 

Spring实现AOP:

  需要导入依赖包:

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

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

</beans>

  方式一:使用Spring的API接口

Service:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/30 21:30
 */
public interface UserService {
    public void add();

    public void deleted();

    public void update();

    public void query();
}

  

ServiceImpl:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/30 21:30
 */
public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("增加了一个用户");
    }

    @Override
    public void deleted() {
        System.out.println("删除了一个用户");

    }

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

    }

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

    }
}

 

实现 AfterReturningAdvice 接口类:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/30 21:38
 */
public class AfterLog implements AfterReturningAdvice {
    /**
     * Callback after a given method successfully returned.
     *
     * @param returnValue the value returned by the method, if any
     * @param method      the method being invoked
     * @param args        the arguments to the method
     * @param target      the target of the method invocation. May be {@code null}.
     * @throws Throwable if this object wishes to abort the call.
     *                   Any exception thrown will be returned to the caller if it's
     *                   allowed by the method signature. Otherwise the exception
     *                   will be wrapped as a runtime exception.
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了" + method.getName() + "返回结果为:" + returnValue);
    }
}

  

实现 MethodBeforeAdvice 接口类:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/30 21:34
 */
public class Log implements MethodBeforeAdvice {

    /**
     * @param method  要执行的对象
     * @param objects 参数
     * @param target  目标对象
     * @author zhx
     * @date 2021-08-30 21:35:40
     */
    @Override
    public void before(Method method, Object[] objects, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + "的" + method.getName() + "被执行了");
    }
}

  

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


    <bean id="userService" class="com.chuxin.service.UserServiceImpl"/>
    <bean id="log" class="com.chuxin.log.Log"/>
    <bean id="afterlog" class="com.chuxin.log.AfterLog"/>

    <!--需要引入aop约束-->
    <aop:config>
        <!--切入点: expression: 表达式,execution(要执行的位置! * * * *)-->
        <aop:pointcut id="pointcut" expression="execution(* com.chuxin.service.UserServiceImpl.* (..))"/>
        <!--执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

  

测试:

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/30 21:48
 */
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

///返回结果

com.chuxin.service.UserServiceImpl的add被执行了
增加了一个用户
执行了add返回结果为:null

  

  方式二:自定义类

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/30 22:04
 */
public class DiyPointCut {

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

  

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

    <!--注册bean-->
    <bean id="userService" class="com.chuxin.service.UserServiceImpl"/>
    <bean id="log" class="com.chuxin.log.Log"/>
    <bean id="afterlog" class="com.chuxin.log.AfterLog"/>

    <!--方式一: 使用Spring的API 接口实现-->
    <!--需要引入aop约束-->
    <!--<aop:config>
        <!–切入点: expression: 表达式,execution(要执行的位置! * * * *)–>
        <aop:pointcut id="pointcut" expression="execution(* com.chuxin.service.UserServiceImpl.* (..))"/>
        <!–执行环绕增强–>
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>-->

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

  

方式三:使用注解实现Aop 

@Aspect: 类上加 标注这是一个切面

package com.chuxin.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/31 20:22
 */
@Component // 将此类注入容器
@Aspect // 标注这个类是一个切面
public class AnnotationPointCut {

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

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

    // 在环绕增强中,我们可以给定一个参数,代表我们要获取切入的点
    @Around("execution(* com.chuxin.service.UserServiceImpl.* (..))")
    public void arount(ProceedingJoinPoint joinPoint) {
        System.out.println(""+joinPoint);

    }
}

 

 

applicationContext.xml 配置

  xml 中需要开启 注解支持: 

 <!--开启注解支持-->
 <aop:aspectj-autoproxy/>
<?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">

    <!--注册bean-->
    <bean id="userService" class="com.chuxin.service.UserServiceImpl"/>
    <bean id="log" class="com.chuxin.log.Log"/>
    <bean id="afterlog" class="com.chuxin.log.AfterLog"/>
    
    <!--方式三:通过注解实现-->
    <bean id="annotationPointCut" class="com.chuxin.diy.AnnotationPointCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>
</beans>

 

spring-Mybatis:

  spring 整合 mybatis步骤:

 

1、编写数据源

 <!--DataSource : 使用spring 的数据源替换mybatis的配置  这里使用的KJDBC-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="webro123"/>
    </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"/>
        <!--配置mapper-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

3、配置SqlSessionTemplate (spring-mybatis  核心配置 )

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

4、需要接口加实现类

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/31 22:48
 */
public class UserMapperImpl implements UserMapper {

    private SqlSessionTemplate sqlSession;

    public SqlSessionTemplate getSqlSession() {
        return sqlSession;
    }

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

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

5、将类注入到Spring

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

6、测试使用

/**
 * @description:
 * @author: zhx
 * @created: 2021/08/31 22:32
 */
public class MyTest {

    @Test
    public void test01() throws IOException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper bean = applicationContext.getBean(UserMapper.class);
        List<User> users = bean.selectAll();
        System.out.println(users);
    }
}

注意:可以跟着官网步骤走 http://mybatis.org/spring/zh/index.html

 

声明式事务:

  事务ACID原则:

    原子性

    一致性

    隔离性 : 多个业务可能操作同一个资源,防止数据损坏。

    持久性: 事务一旦提交 结果不受影响,被存储在持久层服务器中。

Spring 中的事务管理:

  声明事务: AOP

  编程事务: 需要在代码中,进行事务管理。

步骤:

1、配置声明式事务:

   <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--数据源-->
        <constructor-arg ref="datasource"/>
    </bean>

2、结合AOP实现事务植入

   </tx:advice>-->
      <tx:advice id="interceptor" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性: new propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="deleted" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <!--只读-->
            <tx:method name="query" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

注意: 须在beans 标签中加入 : 

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

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd

3、配置事务切入 (自定义要切入的类 以及方法)

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

2021-09-01 20:34:44

posted @ 2021-08-28 10:35  初心不负~  阅读(97)  评论(0)    收藏  举报