一、.JPA 获取 Hibernate的session

     try {
session = entityManager.unwrap(Session.class);
} catch (Exception e) {// from transactionTemplate?
//throw new IllegalStateException("No transactional EntityManager available");
EntityManagerFactory entityManagerFactory = jpaTransactionManager.getEntityManagerFactory();
EntityManagerHolder holder;
if(TransactionSynchronizationManager.hasResource(entityManagerFactory)){
holder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(entityManagerFactory);
}else{
holder = new EntityManagerHolder(entityManagerFactory.createEntityManager());
TransactionSynchronizationManager.bindResource(entityManagerFactory, holder);
}
session = holder.getEntityManager().unwrap(Session.class);
}

二、TransactionSynchronizationManager.getResource()

    /**
* Retrieve a resource for the given key that is bound to the current thread.
* @param key the key to check (usually the resource factory)
* @return a value bound to the current thread (usually the active
* resource object), or {@code null} if none
* @see ResourceTransactionManager#getResourceFactory()
*/
public static Object getResource(Object key) {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
Object value = doGetResource(actualKey);
if (value != null && logger.isTraceEnabled()) {
logger.trace("Retrieved value [" + value + "] for key [" + actualKey + "] bound to thread [" +
Thread.currentThread().getName() + "]");
}
return value;
}

三、TransactionSynchronizationUtils.unwrapResourceIfNecessary(key)

    /**
* Unwrap the given resource handle if necessary; otherwise return
* the given handle as-is.
* @see org.springframework.core.InfrastructureProxy#getWrappedObject()
*/
static Object unwrapResourceIfNecessary(Object resource) {
Assert.notNull(resource, "Resource must not be null");
Object resourceRef = resource;
// unwrap infrastructure proxy
if (resourceRef instanceof InfrastructureProxy) {
resourceRef = ((InfrastructureProxy) resourceRef).getWrappedObject();
}
if (aopAvailable) {
// now unwrap scoped proxy
resourceRef = ScopedProxyUnwrapper.unwrapIfNecessary(resourceRef);
}
return resourceRef;
}

四、ScopedProxy

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

<bean id="userManager" class="com.foo.UserManager">
<property name="userPreferences" ref="userPreferences"/>
</bean>

In the preceding example, the singleton bean userManager is injected with a reference to the HTTP Session-scoped bean userPreferences. The salient point here is that the userManager bean is a singleton: it will be instantiated exactly once per container, and its dependencies (in this case only one, the userPreferences bean) are also injected only once. This means that the userManager bean will only operate on the exact same userPreferences object, that is, the one that it was originally injected with.

This is not the behavior you want when injecting a shorter-lived scoped bean into a longer-lived scoped bean, for example injecting an HTTP Session-scoped collaborating bean as a dependency into singleton bean. Rather, you need a single userManager object, and for the lifetime of an HTTP Session, you need a userPreferences object that is specific to said HTTP Session. Thus the container creates an object that exposes the exact same public interface as the UserPreferences class (ideally an object that is a UserPreferences instance) which can fetch the realUserPreferences object from the scoping mechanism (HTTP request, Session, etc.). The container injects this proxy object into the userManagerbean, which is unaware that  this UserPreferences reference is a proxy. In this example, when a UserManager instance invokes a method on the dependency-injected UserPreferences object, it actually is invoking a method on the proxy. The proxy then fetches the real UserPreferences object from (in this case) the HTTP Session, and delegates the method invocation onto the retrieved real UserPreferences object.

引用:spring docs

五、InfrastructureProxy 结构代理

Interface to be implemented by transparent resource proxies that need to be considered as equal to the underlying resource,

for example for consistent lookup key comparisons. Note that this interface does imply such special semantics and does not

constitute a general-purpose mixin!

Such wrappers will automatically be unwrapped for key comparisons in TransactionSynchronizationManager. Only fully transparent

proxies, e.g. for redirection or service lookups, are supposed to implement this interface. Proxies that decorate the target object

with new behavior, such as AOP proxies, do not qualify here!

被认为等同于底层资源的透明资源代理要实现的接口,例如用于一致的查找的关键字比较。注意,这个接口意味着这样的特殊语义,并不构成一般用途的聚合!

这种包装器将在TransactionSynchronizationManager中自动被拆箱来进行关键字比较。只有完全透明的代理,例如 对于重定向或服务查找,应该实现此接口。

使用新行为来装饰目标对象的代理(例如AOP代理)不适用于此处!

spring 自定义事物同步器(一): TransactionSynchronizationManager 解析的更多相关文章

  1. spring自定义事务同步器(二):借助redisson实现自己的同步器

    1. 借助redis的java客户端redisson实现自己的事物同步器 @Override public void lockWithinCurrentTransaction(Object key) ...

  2. [转载]开发 Spring 自定义视图和视图解析器

    原文出处 http://www.ibm.com/developerworks/cn/java/j-lo-springview/ 概述 Spring 3.0 默认包含了多种视图和视图解析器,比如 JSP ...

  3. 这一次搞懂Spring自定义标签以及注解解析原理

    前言 在上一篇文章中分析了Spring是如何解析默认标签的,并封装为BeanDefinition注册到缓存中,这一篇就来看看对于像context这种自定义标签是如何解析的.同时我们常用的注解如:@Se ...

  4. Spring源码-IOC部分-自定义IOC容器及Bean解析注册【4】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  5. spring 自定义解析类

    设计配置属性和JavaBean 编写XSD文件 编写NamespaceHandler和BeanDefinitionParser完成解析工作 编写spring.handlers和spring.schem ...

  6. spring的事物实现

    Spring的事物主要有三个接口 PlatformTransactionManager. 根据TransactionDefinition配置的事物信息创建事物 TransactionDefinitio ...

  7. Spring自定义类扫描器 ClassPathScanningCandidateComponentProvider

    项目中有个需求 读取xml文件,然后 对xml文件进行解析,比如如果是 Gender=0/1的话,分别代表男女. 所以需要在构造函数之后,初始化bean之前进行过滤解析 xml文件: <inte ...

  8. spring 自定义标签的实现

    在我们进行Spring 框架开发中,估计用到最多的就是bean 标签吧,其实在Spring中像<mvc/><context/>这类标签以及在dubbo配置的标签都是属于自定义的 ...

  9. spring基础---->spring自定义初始化(二)

    这里新增了对ref属性的支持,并且过滤了已经解析的元素.人生有两个词很棒,一言不合和不提也罢. spring自定义对ref属性支持 项目的结构如下:新增一个ThirdBean类,修改了ParseXml ...

随机推荐

  1. am335x 无屏实现开关机程序

    因测试需要加入开机次数记录,所以记录一下7816开关机是怎么做的 原理很简单,开机时判断一个记录文件是否存在,如果存在,运行一段代码,将记录开机次数文件的值读出来+1 代码如下: #include & ...

  2. EmWebAdmin 生成流程分析

    继上一篇的简略的说明 EmWebAdmin 的地址以后下载,生成之后,这一篇讲一下该模板的生成流程 // 上一篇地址: http://www.cnblogs.com/chenfulin5/p/6856 ...

  3. 常用jar命令

    JAR包是Java中所特有一种压缩文档.存储格式格式就是.zip包.但是与ZIP包不同的地方是,生成JAR包时候,会自动添加一个META-INF\MANIFEST.MF文件 命令参数jar {c t ...

  4. 机器学习:如何通过Python入门机器学习

    我们都知道机器学习是一门综合性极强的研究课题,对数学知识要求很高.因此,对于非学术研究专业的程序员,如果希望能入门机器学习,最好的方向还是从实践触发. 我了解到Python的生态对入门机器学习很有帮助 ...

  5. 如何解决redis高并发客户端频繁time out?

    解决方案:https://www.zhihu.com/question/24781521

  6. git clone 故障 fatal could not create work tree dir

    问题如上图,原因是openWRT目录权限的问题,该目录是新创建的查看目录权限后发现该目录只对root有读写权限,对所有者及其他用户无读写权限.最简单的chmod 777 openWRT即可解决问题.

  7. css设置背景固定不滚动效果的示例

    css设置背景固定不滚动效果的示例 背景固定不滚动各位看到最多的无非就是QQ空间了,我们在很多的空间都可以看到内容滚动而北京图片不滚动了,下文整理了几个关于背景固定不滚动css代码. 一.css设置背 ...

  8. $ -----JavaScript 中美元符号 $ 的作用

    JavaScript 中美元符号 $ 是什么 1.首先可以用来表示变量,比如变量 var s='asdsd'或var $s='asdasd'; 2.在正则表达式中,它可以匹配结尾:/sa$/.test ...

  9. 将execel表格的数据导入到mysql数据库

    在开发中经常会将现成的execel表格导入到数据库里,否则一个个字段插入填写,太浪费时间,效率很低.本文主要是讲如果将execel表格导入到mysql数据库,希望对各位有所帮助.使用软件:sql工具: ...

  10. JSP 页面中用绝对路径显示图片

    首先,图片和工程不在一个盘符下.图片也不能放到工程下.  在JSP 文件中 <img src="E:/图片/1.jpg"/>  这样是引不到图片的.因为,JSP页面在引 ...