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();
				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。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM