AOP的应用——声明式事务

事务管理器(PlatformTransactionManager)

Spring的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指在配置文件中申明。用在Spring配置文件中声明式的处理事务来代替代码式的处理事务。这样的好处是,事务管理不侵入开发的组件,具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,如果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可;在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译,这样维护起来极其方便。

xml方式实例:

一个老师类

@Getter
@Setter
public class Teacher {
    private Integer id;
    private String tname;

    public Teacher() {
    }

    public Teacher(Integer id, String tname) {
        this.id = id;
        this.tname = tname;
    }

    public Teacher(String tname) {
        this.tname = tname;
    }
}

对数据库操作的类

@Setter
@Getter
public class TeacherImp {
    private JdbcTemplate jdbcTemplate;
    public List<Teacher> querry(){
        List<Teacher> teachers=jdbcTemplate.query("select * from teacher",new BeanPropertyRowMapper<Teacher>(Teacher.class));
        return teachers;
    }
    public int insert(Teacher teacher){
        int result=jdbcTemplate.update("insert into teacher (tname) values (?)",teacher.getTname());
    //事物回滚
    // int a=9/0;
        return result;
    }
}

建一个jdbc.properties连接数据库

jdbc.url=jdbc:mysql://localhost:3306/tushu
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
jdbc.characterEncoding=utf8

xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!-- 通过xml配置声明式事务,我们需要添加tx命名空间 -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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
       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.xsd
 ">

    <!-- 通过xml方式配置Spring声明式事务 配置start -->
    <context:component-scan base-package="com.lanou3g.spring.shiwulianjie"/>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="teacherImp" class="com.lanou3g.spring.shiwulianjie.dao.TeacherImp">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>


    <!-- 第一步:配置数据源 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="${jdbc.url}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="connectionProperties">
            <props>
                <prop key="characterEncoding">${jdbc.characterEncoding}</prop>
            </props>
        </property>
    </bean>

    <!-- 第二步:初始化事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 第三步:配置事务AOP通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="insert*" rollback-for="ArithmeticException" />
          	<!-- 对事务进行回滚-->
            <tx:method name="query*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 第四步:定义AOP配置(将上面的通知和表达式组装到一起) -->
    <aop:config>
        <aop:pointcut id="all_dao_method" expression="execution(* com.lanou3g.spring.shiwulianjie.dao.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="all_dao_method" />
    </aop:config>
    <!-- 通过xml方式配置Spring声明式事务 配置结束 -->
</beans>

使用入口

public class AppTransation {

    public static void main(String[] args) {
        ApplicationContext ctx= new ClassPathXmlApplicationContext("application.xml");
//        testQuery(ctx);
        testTransaction(ctx);
    }
    //查询全部
    static void testQuery(ApplicationContext ctx) {
        TeacherImp teacherImp=ctx.getBean(TeacherImp.class);
        List<Teacher> teachers=teacherImp.querry();
        for (Teacher teacher:teachers){
            System.out.println("id"+teacher.getId()+"name"+teacher.getTname());
        }
    }
    //插入数据
    static void testTransaction(ApplicationContext ctx) {
        TeacherImp teacherImp=ctx.getBean(TeacherImp.class);
        int row=teacherImp.insert(new Teacher("刘备"));
        System.out.println("影响了"+row+"行");
    }
}

注解方式

对数据库操作的类


@Setter
@Getter
@Repository //此注解和@Component作用一样, 只是含有特定的语义(一般用来标注dao层的类)
public class TeacherImp {
	//它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //用于管理事务
    @Transactional(readOnly = true)
    public List<com.lanou3g.spring.shiwulianjie.annotation.bean.Teacher> querry(){
        List<Teacher> teachers=jdbcTemplate.query("select * from teacher",new BeanPropertyRowMapper<Teacher>(Teacher.class));
        return teachers;
    }
    @Transactional(rollbackFor = {ArithmeticException.class})
    public int insert(Teacher teacher){
        int result=jdbcTemplate.update("insert into teacher (tname) values (?)",teacher.getTname());
    //事物回滚
//     int a=9/0;
        return result;
    }

}

配置的数据源


@PropertySource("classpath:jdbc.properties")
@Component
public class MyDataSource extends DriverManagerDataSource{
    public MyDataSource(@Value("${jdbc.driver}") String driver, @Value("${jdbc.url}") String url, @Value("${jdbc.user}") String userName, @Value("${jdbc.password}") String password, @Value("${jdbc.characterEncoding}") String characterEncoding) {
        super.setDriverClassName(driver);
        super.setUrl(url);
        super.setUsername(userName);
        super.setPassword(password);
        Properties conProperties = new Properties();
        conProperties.setProperty("characterEncoding", characterEncoding);
        super.setConnectionProperties(conProperties);
    }
}

使用入口

@Configuration
@ComponentScan(basePackages = "com.lanou3g.spring.shiwulianjie.annotation")
@EnableTransactionManagement
//开启事务相关注解支持
public class AppAnnotation {
    /**
     * 定义JdbcTemplate对象,Spring给我们封装了所有的JDBC操作
     * @param dataSource
     * @return
     */
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    /**
     * 定义事务管理器bean
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
    public static void main(String[] args) {
        ApplicationContext ctx= new AnnotationConfigApplicationContext(AppAnnotation.class);
//        testQuery(ctx);
        testTransaction(ctx);
    }
    static void testQuery(ApplicationContext ctx) {
        TeacherImp teacherImp=ctx.getBean(TeacherImp.class);
        List<Teacher> teachers=teacherImp.querry();
        for (Teacher teacher:teachers){
            System.out.println("id"+teacher.getId()+"name"+teacher.getTname());
        }
    }

    static void testTransaction(ApplicationContext ctx) {
        TeacherImp teacherImp=ctx.getBean(TeacherImp.class);
        int row=teacherImp.insert(new Teacher("关羽"));
        System.out.println("影响了"+row+"行");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值