获取ApplicationContext的方法及手动控制事务提交
来源:互联网 发布:软件层次结构图 编辑:程序博客网 时间:2024/06/02 05:03
首先新建一个类SpringContextHolder.java,类的内容如下,其中setApplicationContext(ApplicationContext applicationContext)会在spring初始化的时候自动调用,这样的好处就是我们不用每次使用ApplicationContext的时候都去重新初始化一次spring,只需要一次便可以了。
package com.taotao.content.utils;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class SpringContextHolder implements ApplicationContextAware {private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextHolder.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); } public static <T>T getBean(String beanName , Class<T>clazz) { return applicationContext.getBean(beanName , clazz); }}写的这个类要在spring配置文件中进行配置,如下所示,这样才能在spring启动的时候去自动给ApplicationContext赋值,否则spring根本就不知道有这么一个类,也不会去自动赋值。
<bean id="springContextHolder" class="com.taotao.content.utils.SpringContextHolder"></bean>在项目中需要用到ApplicationContext的地方,使用如下。
ApplicationContext ctx = SpringContextHolder.getApplicationContext();//获取事务DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) ctx.getBean("transactionManager");DefaultTransactionDefinition def = new DefaultTransactionDefinition();def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务,这样会比较安全些。TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态开启事务后,我们进行业务逻辑处理,处理完之后对事务进行提交,如下所示。
try {//逻辑代码,可以写上你的逻辑处理代码transactionManager.commit(status);} catch (Exception e) {transactionManager.rollback(status);}
0 0
- 获取ApplicationContext的方法及手动控制事务提交
- SpringMVC 手动控制事务提交
- SpringMVC 手动控制事务提交
- SpringMVC 手动控制事务提交
- SpringMVC 手动控制事务提交 --各种坑
- connection的手动提交事务
- 事务的手动提交 jdbc Template
- spring 获取 ApplicationContext的方法
- Spring获取ApplicationContext的方法
- Spring 手动提交事务
- spring中事务传播下,特殊方法手动控制事务
- 手动获取spring的ApplicationContext和bean对象
- 手动获取spring的ApplicationContext和bean对象
- 手动控制事务
- spring手动事务控制
- springmvc mybatis 手动提交事务
- 获取Spring的ApplicationContext的方法
- spring获取ApplicationContext的方法-持续更新
- windows10常用快捷键
- my choice
- FWT 模板
- 题目1117:整数奇偶排序
- ZOJ3767-Elevator
- 获取ApplicationContext的方法及手动控制事务提交
- OracleDB的数据库名,实例名,服务名,数据库域名,全局数据库名的简单介绍
- SVN环境下快速导出增量包(未提交的情况下)
- Unity基础UI--Image
- 数据结构图之五(拓扑排序)
- POJ 1276 Cash Machine(?)
- 【测试】软件测试的流程图&&软件测试基本概念
- TensorFlow函数——tf.variable( )
- R-CNN论文详解