事务的处理方法
大型项目事务处理:
-
在Spring中声明事务的管理对象
<!--此处的id 是自己可随意取的--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--指向数据源--> <property name="dataSource" ref="mySources"/> </bean>
-
声明事务属性
<!--transaction-manager 的值指向事务对象管理器,与事务关联其--> <tx:advice id="myAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--可以存在多个 <tx:method>标签--> <!--事务属性的声明--> <!--name 表示需要配置的事务的名称 可以适应通配符--> <!--isolation表示事物的隔离级别--> <!--rollback-for 回滚的异常--> <!--timeout 超时设置--> <!--propagation 事务的传播--> <!--read-only 仅仅可读 true 表示仅仅可读--> <tx:method name="" isolation="" propagation="" read-only="" rollback-for="" timeout=""/> </tx:attributes> </tx:advice>
-
配置AOP,将事务与AOP联系起来
<tx:advice id="myAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="" isolation="" no-rollback-for="" propagation="" read-only="" rollback-for="" timeout=""/> </tx:attributes> </tx:advice> <!-- AOP 的设置--> <aop:config> <!--此处的作用是声明AOP的切入点--> <!--expression 中可以使用切入表达式--> <aop:pointcut id="123" expression=""/> <!--advice-ref找到需要声明AOP的属性 pointcut-ref指向AOP的位置 --> <aop:advisor advice-ref="myAdvice" pointcut-ref="123"/> </aop:config>
-
解决容器的重复创建问题:
-
创建监听器(web.xml)
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:Spring.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
-
使用相应的工具类得到容器:
此处方法的优势: 容器在使用开始的时候就已经创建了,避免了容器的重复创建。
WebApplicationContext context=null; ServletContext sc=getServletContext(); context= WebApplicationContextUtils.getWebApplicationContext(sc);
作用:
代替原来的容器创建:
ApplicationContext context=new ClassPathXmlApplicationContext("Spring.xml");
以上容器创建的弊端:
1. 每次使用都需要创建新的容器,如果访问量过大,会造成内存的大量消耗(旧的容器还未清理,新的容器已经创建!)