spring声明式事务管理
将业务中的开启事务,提交事务,异常回滚等用事务管理器管理,底层就是aop。
在一个application中注入另外一个配置文件中的bean对象,要通过import导入,或者ctrl+alt+enter导入依赖。
application配置事务管理器:
三步骤:
配置事务管理切面对象,和数据源
配置切面对象的属性和要管理的事务
配置切面
点击查看代码
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 导入applicationContext-->
<import resource="applicationContext.xml"/>
<!-- 配置事务管理器切面对象-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--需要注入数据源对象-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务管理器属性-->
<tx:advice id="txAdvice">
<tx:attributes>
<!-- name:执行受事务控制的方法。配置方式 1,给定完全方法名,通过* 统配符指定方法名-->
<!--propagation:配置事务的传播行为-->
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置切面-->
<aop:config>
<!--配置切点-->
<aop:pointcut id="txPointcut" expression="execution(* com.bjsxt.service.*.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
spring启动时可以加载多个配置文件
点击查看代码
public class test_01 {
public static void main(String[] args) {
//加载多个配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml","applicationContext2.xml");
UsersService usersService = (UsersService) applicationContext.getBean("usersService");
Users users = new Users();
users.setUsername("suibian78");
users.setUsersex("male");
Orders orders = new Orders();
orders.setOrderprice(2800);
usersService.addUserAndOrder(users, orders);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!