使用AspectJ的AOP配置管理事务

it2025-03-19  13

项目目录: application-config.xml(Spring核心配置文件): <!--声明事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="myDataSource"/> </bean> <!--声明事务的通知 id:为通知的名称 --> <tx:advice id="buyAdvice" transaction-manager="transactionManager"> <!-- 指定业务函数的属性(传播行为,隔离级别,超时,回滚等) --> <tx:attributes> <!--给指定业务函数设值事务属性 name:业务函数的名称,可以使用通配符(*) rollback-for:是异常的全限定名 --> <tx:method name="buyGoods" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.NullPointerException, com.bjpowernode.excet.NotEnoughException"/> </tx:attributes> </tx:advice> <!--配置AOP--> <aop:config> <!--声明切入点表达式:指定一些类和函数要加入切面的功能--> <aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/> <!--声明增强器对象(通知和切入点) advice-ref:事务通知对象的id pointcut-ref:切入点表达式 --> <aop:advisor advice-ref="buyAdvice" pointcut-ref="servicePt"/> </aop:config> java测试代码: public static void main(String[] args){ String config="application-config.xml"; ApplicationContext context=new ClassPathXmlApplicationContext(config); BuyGoodsService buyGoodsService=(BuyGoodsService) context.getBean("buyService"); System.out.println("Main:"+buyGoodsService.getClass().getName()); buyGoodsService.buyGoods(1001,200); }
最新回复(0)