Spring入门知识 ———— 使用xml文件的方式配置Spring事务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38111957/article/details/84000554

一、引言

关于事务的最后一个章节,如何在xml当中配置一个事务。

从IOC、AOP、到事务,都会有基于xml方式和注解的方式进行实现,可见Spring 还是很灵活的。

今天所介绍xml配置事务也是很简单的,记住以下步骤即可:

步骤一:配置事务管理器

步骤二:配置事务相关属性

步骤三:配置事务应用切点

是不是炒鸡简单

二、具体的xml配置

还是基于之前的案例进行演示的哟。

<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

    <!--引入外部属性文件-->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!--开启注解扫描包-->
    <context:component-scan base-package="com.spring.five"></context:component-scan>

    <!--配置阿里巴巴连接池-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="driverClassName" value="${jdbc.driver}"></property>
    </bean>

    <!--配置JdbcTemplate-->
    <bean class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>

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

   <!-- 配置事务属性-->
    <tx:advice id = "txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--针对具体的某一个方法,也可以设置相关属性-->
            <tx:method name="goShopping" timeout="3"></tx:method>
            <!--针对所有的方法-->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务应用切点-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.spring.five.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
    </aop:config>
</beans>

猜你喜欢

转载自blog.csdn.net/weixin_38111957/article/details/84000554