spring的@PersistenceUnit和@PersistenceContext
前提:spring注⼊了PersistenceAnnotationBeanPostProcessor,或者⾃定义⼀个继承PersistenceAnnotationBeanPostProcessor的⼦类,然后注⼊到spring 中,但只能存在⼀个。
1.当field上使⽤了@PersistenceUnit和@PersistenceContext,使⽤PersistenceAnnotationBeanPostProcessor进⾏解析。
2.在PersistenceAnnotationBeanPostProcessor有内部类PersistenceElement。spring会构造⼀个PersistenceElement实例。
public PersistenceElement(Member member, PropertyDescriptor pd) {
super(member, pd);
AnnotatedElement ae = (AnnotatedElement) member;
PersistenceContext pc = ae.getAnnotation(PersistenceContext.class);
PersistenceUnit pu = ae.getAnnotation(PersistenceUnit.class);
Class<?> resourceType = EntityManager.class;
if (pc != null) {
if (pu != null) {
throw new IllegalStateException("Member may only be annotated with either " +
"@PersistenceContext or @PersistenceUnit, not both: " + member);
}
Properties properties = null;
PersistenceProperty[] pps = pc.properties();
if (!ObjectUtils.isEmpty(pps)) {
properties = new Properties();
for (PersistenceProperty pp : pps) {
properties.setProperty(pp.name(), pp.value());
}
}
this.unitName = pc.unitName();
spring怎么读取propertiesthis.properties = properties;
}
else {
resourceType = EntityManagerFactory.class;
this.unitName = pu.unitName();
}
checkResourceType(resourceType);
}
3.PersistenceElement实例⽣成后。调⽤PersistenceElement的getResourceToInject⽅法,返回相应的对象。
protected Object getResourceToInject(Object target, String requestingBeanName) {
// Resolves to EntityManagerFactory or EntityManager.
if (pe != null) {
return (pe == PersistenceContextType.EXTENDED ?
resolveExtendedEntityManager(target, requestingBeanName) :
resolveEntityManager(requestingBeanName));
}
else {
// OK, so we need
return resolveEntityManagerFactory(requestingBeanName);
}
}
如果pe为空返回EntityManagerFactory,否则,根据type类型返回不同的EntityManager,如果你使⽤的@PersistenceContext注解,则type必有值,默认是TRANSACTION。
4.⾄于如何⽣成这个EntityManagerFactory或者EntityManager,请参阅PersistenceAnnotationBeanPostProcessor中相应⽅法的源码,例
如resolveExtendedEntityManager。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论