前提: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();
this.type = pc.type();
this.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 (this.type != null) { return (this.type == PersistenceContextType.EXTENDED ? resolveExtendedEntityManager(target, requestingBeanName) : resolveEntityManager(requestingBeanName)); } else { // OK, so we need an EntityManagerFactory... return resolveEntityManagerFactory(requestingBeanName); } }
如果this.type为空返回EntityManagerFactory,否则,根据type类型返回不同的EntityManager,如果你使用的@PersistenceContext注解,则type必有值,默认是TRANSACTION。
4.至于如何生成这个EntityManagerFactory或者EntityManager,请参阅PersistenceAnnotationBeanPostProcessor中相应方法的源码,例如resolveExtendedEntityManager。