实际使用场景:为了避免java中间件或者前台程序出错而数据库数据依旧成功修改这种情况出现,要使用spring的事务管理组件防止数据出错
第零步:引入jar包(cglib包必须引入,否则aop会失效,织入不成功)
第一步:配置数据源连接池(这里采用的c3p0连接池)
<!-- 加载数据库文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 获取信息 -->
<bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="driverClass" value="${jdbc.driver}"></property>
</bean>
第二步:定义transactionManager这个bean(事务管理器常用的有四种,hibernate的、jta的、jdo的、jdbc的,这里我直接选用Jdbc的)
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="comboPooledDataSource" />
</bean>
第三步:设置自动代理(不设置自动代理,aop会失效)
<aop:aspectj-autoproxy proxy-target-class="true"/>
第四步:使用tx标签配置拦截器(aspectj表达式必须准确,否则aop织入会失效)
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<!-- 原来是写com.web.service,实际上项目的package是com.web.Service -->
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.web.Service.*.*(..))" />
</aop:config>
补充说明:如果同时使用事务管理切面和日志输出切面的话,可以这么配置,同时写两个aop:config
<bean id = "logAspect" class = "com.web.aspect.LogAspect"></bean>
<aop:config>
<aop:aspect id="LogAspect" ref="logAspect">
<aop:pointcut expression="execution(* com.web.Service.*.*(..))" id="logPointCut"/>
<!-- 原来是写com.web.service,实际上项目的package是com.web.Service -->
<aop:before method="doBefore" pointcut-ref="logPointCut"/>
<aop:after method="after" pointcut-ref="logPointCut"/>
<aop:around method="Around" pointcut-ref="logPointCut"/>
<aop:after-returning method="AfterReturning" pointcut-ref="logPointCut"/>
<aop:after-throwing method="AfterThrowing" pointcut-ref="logPointCut" throwing="error"/>
</aop:aspect>
</aop:config>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.web.Service.*.*(..))" />
</aop:config>