Spring基础--基于注解配置的spring自带的声明式事务控制

在原来基于XML配置的基础上进行修改:XML配置的事务控制
1、修改持久层实现类
在基于XML的配置中,持久层实现类AccountImpl在使用jdbcTemplate是使用其继承的父类JdbcDaoTemplate的方法来获取jdbcTemplate来进行查询,但在注解配置中,我们从容器中导入jdbcTemplate,同时获取数据源。
在这里插入图片描述
2、将bean.xml配置中对应的配置使用注解
在这里插入图片描述
修改后的bean.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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置spring要扫描的包-->
    <context:component-scan base-package="org.example"></context:component-scan>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://121.41.229.122:3306/spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>


    <!-- 配置JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- spring中基于注解的声明式事务控制配置步骤
     1,配置事务管理器
     2.开启spring对注解事务的支持
     3.在需要事务支持的地方使用@Transactional注解
     -->


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

    <!-- 开启spring对注解事务的支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

总结:从XML配置再到注解配置,可以看出,有的配置确实是注解配置方便,一个注解注入容器,但有些配置就比较麻烦,就比如上述的事务通知的属性,在注解中可选择通配的方式对函数名筛选配置,而在注解中只能一个一个配置。

猜你喜欢

转载自blog.csdn.net/qq_44660367/article/details/108807734