Spring_使用XML文件的方式配置事务

步骤:

  1. 正常配置jdbctemplate
  2. 正常配置bean
  3. 配置事物管理器
  4. 配置事物管理器
  5. 配置aop切入点,通过切入点把事物链接起来

思路:

接着上一个买书的例子吧,直接拷到新包下,把注解都干掉,需要自动引入的直接set方法

package com.spring.bean;

public interface BookShopDao {

    //根据书号获取书的单价
    public int findBookPriceByIsbn(String isbn);
    
    //更新数的库存. 使书号对应的库存 - 1
    public void updateBookStock(String isbn);
    
    //更新用户的账户余额: 使 username 的 balance - price
    public void updateUserAccount(String username, int price);
}
package com.spring.bean;

import org.springframework.jdbc.core.JdbcTemplate;

public class BookShopDaoImpl implements BookShopDao {

    private JdbcTemplate jdbcTemplate;
    
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public int findBookPriceByIsbn(String isbn) {
        String sql = "SELECT price FROM book WHERE isbn = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
    }

    @Override
    public void updateBookStock(String isbn) {
        //检查书的库存是否足够, 若不够, 则抛出异常
        String sql2 = "SELECT stock FROM book_stock WHERE isbn = ?";
        int stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);
        if(stock == 0){
            throw new BookStockException("库存不足!");
        }
        
        String sql = "UPDATE book_stock SET stock = stock -1 WHERE isbn = ?";
        jdbcTemplate.update(sql, isbn);
    }

    @Override
    public void updateUserAccount(String username, int price) {
        //验证余额是否足够, 若不足, 则抛出异常
        String sql2 = "SELECT balance FROM account WHERE username = ?";
        int balance = jdbcTemplate.queryForObject(sql2, Integer.class, username);
        if(balance < price){
            throw new UserAccountException("余额不足!");
        }
        
        String sql = "UPDATE account SET balance = balance - ? WHERE username = ?";
        jdbcTemplate.update(sql, price, username);
    }

}
package com.spring.bean;

public interface BookShopService {
    
    public void purchase(String username, String isbn);
    
}
package com.spring.bean;

public class BookShopServiceImpl implements BookShopService {

    private BookShopDao bookShopDao;
    public void setBookShopDao(BookShopDao bookShopDao) {
        this.bookShopDao = bookShopDao;
    }
    @Override
    public void purchase(String username, String isbn) {
        
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {}
        
        //1. 获取书的单价
        int price = bookShopDao.findBookPriceByIsbn(isbn);
        
        //2. 更新数的库存
        bookShopDao.updateBookStock(isbn);
        
        //3. 更新用户余额
        bookShopDao.updateUserAccount(username, price);
    }

}
package com.spring.bean;

import java.util.List;

public interface Cashier {

    public void checkout(String username, List<String> isbns);
    
}
package com.spring.bean;

import java.util.List;

public class CashierImpl implements Cashier {

    private BookShopService bookShopService;
    public void setBookShopService(BookShopService bookShopService) {
        this.bookShopService = bookShopService;
    }
    @Override
    public void checkout(String username, List<String> isbns) {
        for(String isbn: isbns){
            bookShopService.purchase(username, isbn);
        }
    }

}

自定义异常不贴了,和上节代码一样

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"
    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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        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-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
    
    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    
    <!-- 配置 mysql 数据源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
    </bean>
    
    <!-- 配置 Spirng 的 JdbcTemplate -->
    <bean id="jdbcTemplate" 
        class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <!-- 配置 NamedParameterJdbcTemplate, 该对象可以使用具名参数, 其没有无参数的构造器, 所以必须为其构造器指定参数 -->
    <bean id="namedParameterJdbcTemplate"
        class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"></constructor-arg>    
    </bean>
    <!-- 配置bean -->
    <bean id="bookShopDao" class="com.spring.bean.BookShopDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
    <bean id="bookShopService" class="com.spring.bean.BookShopServiceImpl">
        <property name="bookShopDao" ref="bookShopDao"></property>
    </bean>
    <bean id="cashier" class="com.spring.bean.CashierImpl">
        <property name="bookShopService" ref="bookShopService"></property>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事物属性 -->
    <tx:advice id="txadvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="purchase" propagation="REQUIRES_NEW"/>
            <tx:method name="find*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事物切入点,把事物通过切入点连接起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.spring.bean.*.*(..))" 
            id="txPointCut"/>
        <aop:advisor advice-ref="txadvice" pointcut-ref="txPointCut"/>    
    </aop:config>
<!--     <aop:config>
        <aop:pointcut expression=" execution(* com.spring.bean.* . *(..))" id="pointcut"/>
        <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"/>
    </aop:config> -->
    
</beans>

注意,

如果配置文件正确,报错空指针异常,一般是@Autowired的实体,,没用set方法创建实体

报错信息如下:

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 15 in XML document from class path resource [beans.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 15; columnNumber: 15; cvc-complex-type.2.4.c: 通配符的匹配很全面, 但无法找到元素 'aop:config' 的声明。

一般是配置文件的顶部没有导入相应的aop schema命名空间,把命名空间加上即可。

 

posted @ 2017-01-18 21:25  久曲健  阅读(1628)  评论(0编辑  收藏  举报