准备:jdbc.properties
第一步:配置连接对象
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
第二步:编写实体
//Dao层
public class AccountDao extends JdbcDaoSupport {
//出钱
public void out(String name,double monney){
String sql="update account set monney=monney-? where name=? ";
Object[] paramarr={monney,name};
this.getJdbcTemplate().update(sql,paramarr);
}
//金钱
public void in(String name,double monney){
String sql="update account set monney=monney+? where name=? ";
Object[] paramarr={monney,name};
this.getJdbcTemplate().update(sql,paramarr);
}
}
//service层
public class AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao){
this.accountDao=accountDao;
}
public void transaction(String name1,String name2,Double monney){
accountDao.out(name1,monney);
int num=1/0;
accountDao.in(name2,monney);
}
}
第三步:applicationContext.xml 配置Dao和service层
//将Dao层交给spring进行管理(配置Dao层)
<bean id="accountDao" class="it.heima.dao.AccountDao">
<property name="dataSource" ref="dataSource"/>
</bean>
//将Service层交给spring进行管理(配置Service层)
<bean id="accountService" class="it.heima.service.AccountService">
<property name="accountDao" ref="accountDao"/>
</bean>
第四步:配置增强类
<!--配置增强类,通知-->
<tx:advice id="txadvice" transaction-manager="transactionManager">
<tx:attributes>
//增强类中需要增强普通类的方法
<tx:method name="transaction"/>
</tx:attributes>
</tx:advice>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--将数据源作为参数-->
<property name="dataSource" ref="dataSource"/>
</bean>
第五步:让增强类和普通类产生关系
<aop:config proxy-target-class="false">
<aop:advisor advice-ref="txadvice" pointcut="bean(*Service)"/>
</aop:config>