Spring学习笔记3

一、属性占位符

1.注入DataSource

使用DataSource的案例,给数据源注入Property中的数据:

需求:给DBCP的DataSource注入值: BasicDataSource.
拷jar:
   mysql驱动包.
   dbcp.jar
   pool.jar
配置文件(进行注入)
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql:///admindb" />
        <property name="username" value="root" />
        <property name="password" value="123" />
    </bean>
Test类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class propertyPlaceHolderTest {
    @Autowired
    private DataSource dataSource;
    @Test
    public void testConnection() throws SQLException{
        System.out.println(dataSource.getConnection());
    }
}

注意:注入时,property中name的属性值要与BasicDataSource属性值相同。

2.属性占位符配置

1,引入context命名空间
<?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: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/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            ">  

3.提供db.properties文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///admindb
jdbc.username=root
jdbc.password=123
jdbc.initialSize=5

4.通过<context:property-placeholder location="classpath:db.properties"/>找到文件.

5.设置占位符

<context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${jdbc.initialSize}" />
    </bean>

二、事务(xml配置)

1.模拟转账

AccountDao

package cn.wzk.tx;

public interface AccountDao {
    // 转入
    void transIn(Integer id, Integer money);

    // 转出
    void transOut(Integer id, Integer money);
}

AccountDaoImpl

package cn.wzk.tx;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    // 转入
    public void transIn(Integer id, Integer money) {
        String sql = "update account set balance= balance + ? where id = ?";
        Object[] args = {money,id};
        super.getJdbcTemplate().update(sql, args);
    }

    // 转出
    public void transOut(Integer id, Integer money) {
        String sql = "update account set balance= balance - ? where id = ?";
        Object[] args = {money,id};
        super.getJdbcTemplate().update(sql, args);
    }

}

AccountService

package cn.wzk.tx;

public interface AccountService {
    /**
     * 转钱
     * @param outId     :转出账号
     * @param inId      :转入账号
     * @param money     :转出/转入金额
     */
    void trans(Integer outId,Integer inId,Integer money);

}

AccountServiceImpl

package cn.wzk.tx;

public class AccountServiceImpl implements AccountService {

    public void trans(Integer outId, Integer inId, Integer money) {
        dao.transIn(inId, money);
        //int i = 1/0;                 //模拟停电
        dao.transOut(outId, money);
    }
    private AccountDao dao;

    public void setDao(AccountDao dao) {
        this.dao = dao;
    }

}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" 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.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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        ">

    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 配置DataSource -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

    <bean id="baseDao" abstract="true">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="accountDao" class="cn.wzk.tx.AccountDaoImpl" parent="baseDao" />

    <bean id="accountService" class="cn.wzk.tx.AccountServiceImpl">
        <property name="dao" ref="accountDao" />
    </bean>

</beans>

测试

package cn.wzk.tx;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TxTest {
    @Test
    public void test(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        AccountService service = ac.getBean("accountService",AccountService.class);
        service.trans(10086,10010,1000);   //转出账号,转入账号,转出金额
    }
}
以上存在的问题是,当我们在转账的时候模拟停电时(int i =1/0)
dao.transIn(inId, money);已经正常执行,而后面就无法执行到了,这就造成了转出者没有减少钱,转入者增加了钱,这是绝对不允许出现的。
**Spring对事务有很好的支持,提供了事务管理器,PlatformTransactionManager:平台事务管理器(顶层接口),我们常用的是他的实现类有DataSourceTransactionManager和HibernateTransactionManager**

2.配置事务管理(交给Spring进行管理)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" 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.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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        ">

    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 配置DataSource -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

    <!-- 1.配置事务管理器(AOP:做什么) -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 2.配置通知(AOP:时机,本质是一个环绕通知) -->
    <tx:advice id="crudAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="trans" />
        </tx:attributes>
    </tx:advice>
    <!-- 3.配置通知的地点(AOP:在哪里增强) -->
    <aop:config>
        <aop:pointcut expression="execution(* cn.wzk.tx.*Service.*(..))"
            id="txPoint" />
        <aop:advisor advice-ref="crudAdvice" pointcut-ref="txPoint" />
    </aop:config>

    <bean id="baseDao" abstract="true">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="accountDao" class="cn.wzk.tx.AccountDaoImpl" parent="baseDao" />

    <bean id="accountService" class="cn.wzk.tx.AccountServiceImpl">
        <property name="dao" ref="accountDao" />
    </bean>

</beans>

3.事务的配置属性

<!-- 2.配置通知(AOP:时机,本质是一个环绕通知) -->
    <tx:advice id="crudAdvice" transaction-manager="txManager">
        <tx:attributes>
            <!-- 
                无论DML操作还是DQL(查询)操作,都放在事务中
                事务都是开在业务逻辑层的(Service)

                1.name:增强的方法名(支持通配符) eg :trans*(表示以trans开头的所有方法)
                2.isolation:事务的隔离级别,默认就使用DEFAULT:表示数据库本身的隔离级别
                              其他的属性值:都是Spring模拟出来的
                           不配置(使用缺省的)
                3.read-only:查询的时候设置为true,提高性能,缺省是false
                4.propagation:事务的传播规则
                            REQUIRED 缺省值
                            REQUIRES_NEW 不管是否存在事务都要重新发起一个事务(原来的事务先挂起)
                                        保存数据的时候建议使用
                5.rollback-for:写异常类的全限类名;遇见该异常要回滚事务,Spring中默认只能回滚
                               RuntimeException及其子类,不能回滚(Exception,Throwable)
                                    这就要求我们在service中,只能使用RuntimeException,若异常不是该异常
                                   重新包装成RuntimeException
                6.no-rollback-for:写异常类的全限类名;遇见该异常不回滚
             -->            
            <tx:method name="trans" read-only="false" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

最后写一个crud通用通知

<tx:advice>
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRES_NEW"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="list*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
</tx:advice>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值