Top Description Inners Fields Constructors Methods
org.springframework.orm.jpa.support

public Class PersistenceAnnotationBeanPostProcessor

extends Object
implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, BeanRegistrationAotProcessor, PriorityOrdered, BeanFactoryAware, Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable, org.springframework.beans.factory.BeanFactoryAware, org.springframework.beans.factory.Aware, org.springframework.core.PriorityOrdered, org.springframework.core.Ordered, org.springframework.beans.factory.aot.BeanRegistrationAotProcessor, org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor, org.springframework.beans.factory.config.BeanPostProcessor, org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor, org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
Annotations
@SuppressWarnings:serial
Imports
java.beans.PropertyDescriptor, java.io.Serializable, java.lang.reflect.AnnotatedElement, .Member, .Method, .Modifier, java.util.ArrayList, .Arrays, .Collection, .List, .Map, .Properties, .TreeSet, java.util.concurrent.ConcurrentHashMap, jakarta.persistence.EntityManager, .EntityManagerFactory, .PersistenceContext, .PersistenceContextType, .PersistenceProperty, .PersistenceUnit, .SynchronizationType, org.springframework.aot.generate.GeneratedClass, .GeneratedMethod, .GeneratedMethods, .GenerationContext, .MethodReference.ArgumentCodeGenerator, org.springframework.aot.hint.RuntimeHints, org.springframework.beans.BeanUtils, .PropertyValues, org.springframework.beans.factory.BeanCreationException, .BeanFactory, .BeanFactoryAware, .ListableBeanFactory, .NoSuchBeanDefinitionException, org.springframework.beans.factory.annotation.InjectionMetadata, .InjectionMetadata.InjectedElement, org.springframework.beans.factory.aot.BeanRegistrationAotContribution, .BeanRegistrationAotProcessor, .BeanRegistrationCode, org.springframework.beans.factory.config.ConfigurableBeanFactory, .ConfigurableListableBeanFactory, .DestructionAwareBeanPostProcessor, .InstantiationAwareBeanPostProcessor, .NamedBeanHolder, org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor, .RegisteredBean, .RootBeanDefinition, org.springframework.core.BridgeMethodResolver, .Ordered, .PriorityOrdered, org.springframework.core.annotation.AnnotationUtils, org.springframework.javapoet.CodeBlock, .MethodSpec, org.springframework.jndi.JndiLocatorDelegate, .JndiTemplate, org.springframework.lang.Nullable, org.springframework.orm.jpa.EntityManagerFactoryInfo, .EntityManagerFactoryUtils, .EntityManagerProxy, .ExtendedEntityManagerCreator, .SharedEntityManagerCreator, org.springframework.util.Assert, .ClassUtils, .CollectionUtils, .ObjectUtils, .ReflectionUtils, .StringUtils

BeanPostProcessor that processes jakarta.persistence.PersistenceUnit and jakarta.persistence.PersistenceContext annotations, for injection of the corresponding JPA resources jakarta.persistence.EntityManagerFactory and jakarta.persistence.EntityManager. Any such annotated fields or methods in any Spring-managed object will automatically be injected.

This post-processor will inject sub-interfaces of EntityManagerFactory and EntityManager if the annotated fields or methods are declared as such. The actual type will be verified early, with the exception of a shared ("transactional") EntityManager reference, where type mismatches might be detected as late as on the first actual invocation.

Note

In the present implementation, PersistenceAnnotationBeanPostProcessor only supports @PersistenceUnit and @PersistenceContext with the "unitName" attribute, or no attribute at all (for the default unit). If those annotations are present with the "name" attribute at the class level, they will simply be ignored, since those only serve as deployment hint (as per the Jakarta EE specification).

This post-processor can either obtain EntityManagerFactory beans defined in the Spring application context (the default), or obtain EntityManagerFactory references from JNDI ("persistence unit references"). In the bean case, the persistence unit name will be matched against the actual deployed unit, with the bean name used as fallback unit name if no deployed name found. Typically, Spring's org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean will be used for setting up such EntityManagerFactory beans. Alternatively, such beans may also be obtained from JNDI, e.g. using the jee:jndi-lookup XML configuration element (with the bean name matching the requested unit name). In both cases, the post-processor definition will look as simple as this:

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
In the JNDI case, specify the corresponding JNDI names in this post-processor's "persistenceUnits" map, typically with matching persistence-unit-ref entries in the Jakarta EE deployment descriptor. By default, those names are considered as resource references (according to the Jakarta EE resource-ref convention), located underneath the "java:comp/env/" namespace. For example:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
  <property name="persistenceUnits">
    <map/gt;
      <entry key="unit1" value="persistence/unit1"/>
      <entry key="unit2" value="persistence/unit2"/>
    </map/gt;
  </property>
</bean>
In this case, the specified persistence units will always be resolved in JNDI rather than as Spring-defined beans. The entire persistence unit deployment, including the weaving of persistent classes, is then up to the Jakarta EE server. Persistence contexts (i.e. EntityManager references) will be built based on those server-provided EntityManagerFactory references, using Spring's own transaction synchronization facilities for transactional EntityManager handling (typically with Spring's @Transactional annotation for demarcation and org.springframework.transaction.jta.JtaTransactionManager as backend).

If you prefer the Jakarta EE server's own EntityManager handling, specify entries in this post-processor's "persistenceContexts" map (or "extendedPersistenceContexts" map, typically with matching persistence-context-ref entries in the Jakarta EE deployment descriptor. For example:

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
  <property name="persistenceContexts">
    <map/gt;
      <entry key="unit1" value="persistence/context1"/>
      <entry key="unit2" value="persistence/context2"/>
    </map/gt;
  </property>
</bean>
If the application only obtains EntityManager references in the first place, this is all you need to specify. If you need EntityManagerFactory references as well, specify entries for both "persistenceUnits" and "persistenceContexts", pointing to matching JNDI locations.

NOTE: In general, do not inject EXTENDED EntityManagers into STATELESS beans, i.e. do not use @PersistenceContext with type EXTENDED in Spring beans defined with scope 'singleton' (Spring's default scope). Extended EntityManagers are not thread-safe, hence they must not be used in concurrently accessed beans (which Spring-managed singletons usually are).

Note

A default PersistenceAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom PersistenceAnnotationBeanPostProcessor bean definition.

Authors
Rod Johnson, Juergen Hoeller, Stephane Nicoll, Phillip Webb
Since
2.0
See Also
jakarta.persistence.PersistenceUnit, jakarta.persistence.PersistenceContext

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
private class
PersistenceAnnotationBeanPostProcessor.LocatorDelegate

Separate inner class to isolate the JNDI API dependency (for compatibility with Google App Engine's API white list).

private class
PersistenceAnnotationBeanPostProcessor.PersistenceElement

Class representing injection information about an annotated field or setter method.

Field Summary

Modifier and TypeField and Description
private transient ListableBeanFactory
private transient String
private final Map<Object, EntityManager>
private transient Map<String, String>
private final transient Map<String, InjectionMetadata>
private Object
private int
private transient Map<String, String>
private transient Map<String, String>
private boolean

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
private InjectionMetadata
protected EntityManagerFactory

Returns:

the default EntityManagerFactory
findDefaultEntityManagerFactory
(String requestingBeanName)

Find a single default EntityManagerFactory in the Spring application context.

protected EntityManagerFactory

Returns:

the EntityManagerFactory
findEntityManagerFactory
(String
the name of the persistence unit (may be null or empty)
unitName
,
String
the name of the requesting bean
requestingBeanName
)

Find an EntityManagerFactory with the given name in the current Spring application context, falling back to a single default EntityManagerFactory (if any) in case of no unit name specified.

private InjectionMetadata
findInjectionMetadata(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName)

protected EntityManagerFactory

Returns:

the EntityManagerFactory
findNamedEntityManagerFactory
(String
the name of the persistence unit (never empty)
unitName
,
String
the name of the requesting bean
requestingBeanName
)

Find an EntityManagerFactory with the given name in the current Spring application context.

private InjectionMetadata
public int
getOrder()

Implements org.springframework.core.Ordered.getOrder.

Get the order value of this object.

protected EntityManager

Returns:

the corresponding EntityManager, or null if none found
getPersistenceContext
(String
the name of the persistence unit
unitName
,
boolean
whether to obtain an extended persistence context
extended
)

Return a specified persistence context for the given unit name, as defined through the "persistenceContexts" (or "extendedPersistenceContexts") map.

protected EntityManagerFactory

Returns:

the corresponding EntityManagerFactory, or null if none found
getPersistenceUnit
(String
the name of the persistence unit
unitName
)

Return a specified persistence unit for the given unit name, as defined through the "persistenceUnits" map.

protected <T> T

Returns:

the obtained object
lookup
(String
the JNDI name to look up
jndiName
,
Class<T>
the required type of the object
requiredType
)

Perform a JNDI lookup for the given resource by name.

public void
postProcessBeforeDestruction(Object
the bean instance to be destroyed
bean
,
String
the name of the bean
beanName
)

Implements org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor.postProcessBeforeDestruction.

Apply this BeanPostProcessor to the given bean instance before its destruction, e.g. invoking custom destruction callbacks.

public void
postProcessMergedBeanDefinition(RootBeanDefinition
the merged bean definition for the bean
beanDefinition
,
Class<?>
the actual type of the managed bean instance
beanType
,
String
the name of the bean
beanName
)

Implements org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition.

Post-process the given merged bean definition for the specified bean.

public PropertyValues
postProcessProperties(PropertyValues
the property values that the factory is about to apply (never null)
pvs
,
Object
the bean instance created, but whose properties have not yet been set
bean
,
String
the name of the bean
beanName
)

Overrides default org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor.postProcessProperties.

Post-process the given property values before the factory applies them to the given bean.

public BeanRegistrationAotContribution
processAheadOfTime(RegisteredBean
the registered bean to process
registeredBean
)

Implements org.springframework.beans.factory.aot.BeanRegistrationAotProcessor.processAheadOfTime.

Process the given RegisteredBean instance ahead-of-time and return a contribution or null.

public boolean
requiresDestruction(Object
the bean instance to check
bean
)

Overrides default org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor.requiresDestruction.

Determine whether the given bean instance requires destruction by this post-processor.

public void
resetBeanDefinition(String
the name of the bean
beanName
)

Overrides default org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor.resetBeanDefinition.

A notification that the bean definition for the specified name has been reset, and that this post-processor should clear any metadata for the affected bean.

public void
setBeanFactory(BeanFactory
owning BeanFactory (never null). The bean can immediately call methods on the factory.
beanFactory
)

Implements org.springframework.beans.factory.BeanFactoryAware.setBeanFactory.

Callback that supplies the owning factory to a bean instance.

public void
setDefaultPersistenceUnitName(String unitName)

Specify the default persistence unit name, to be used in case of no unit name specified in an @PersistenceUnit / @PersistenceContext annotation.

public void
setExtendedPersistenceContexts(Map<String, String> extendedPersistenceContexts)

Specify the extended persistence contexts for EntityManager lookups, as a Map from persistence unit name to persistence context JNDI name (which needs to resolve to an EntityManager instance).

public void
setJndiEnvironment(Properties jndiEnvironment)

Set the JNDI environment to use for JNDI lookups.

public void
setJndiTemplate(Object jndiTemplate)

Set the JNDI template to use for JNDI lookups.

public void
setOrder(int order)

public void
setPersistenceContexts(Map<String, String> persistenceContexts)

Specify the transactional persistence contexts for EntityManager lookups, as a Map from persistence unit name to persistence context JNDI name (which needs to resolve to an EntityManager instance).

public void
setPersistenceUnits(Map<String, String> persistenceUnits)

Specify the persistence units for EntityManagerFactory lookups, as a Map from persistence unit name to persistence unit JNDI name (which needs to resolve to an EntityManagerFactory instance).

public void
setResourceRef(boolean resourceRef)

Set whether the lookup occurs in a Jakarta EE container, i.e. if the prefix "java:comp/env/" needs to be added if the JNDI name doesn't already contain it.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait