EntityManager manual injection pattern¶
The EntityManager manual injection pattern is a technique used to explicitly provide an EntityManager instance to a repository or data access object programmatically, rather than relying solely on standard constructor injection or Spring's automatic @PersistenceContext processing.^[600-developer__java__application-server__weblogic__weblogic-spring-jpa.md]
Implementation¶
This pattern typically utilizes Java Reflection API to bypass standard encapsulation. The process involves three main steps: acquiring the target bean instance from the application context, retrieving the EntityManager bean, and forcibly assigning the EntityManager to the target bean's private field^[600-developer__java__application-server__weblogic__weblogic-spring-jpa.md].
Code Example¶
The following implementation demonstrates how to inject the EntityManager into a generic bean type using reflection^[600-developer__java__application-server__weblogic__weblogic-spring-jpa.md]:
private <T> T getBean(Class<T> clazz) {
// 1. Retrieve the target bean instance
T bean = anno.getBean(clazz);
// 2. Retrieve the EntityManager from the context
EntityManager em = anno.getBean(EntityManager.class);
// 3. Use reflection to locate the private field
Field field = ReflectionUtils.findField(clazz, "em");
field.setAccessible(true);
// 4. Inject the EntityManager instance
ReflectionUtils.setField(field, bean, em);
return bean;
}
Usage Context¶
This approach is particularly useful when a custom Repository implementation (e.g., CustomerProfileRepository) is instantiated as a standard Spring Bean but requires an EntityManager to execute JPA queries^[600-developer__java__application-server__weblogic__weblogic-spring-jpa.md].
For example, in a test case or configuration where automatic wiring is not applied, the manual injection ensures the repository has the necessary dependencies to perform operations like findLevelId^[600-developer__java__application-server__weblogic__weblogic-spring-jpa.md]:
CustomerProfileRepository customerProfileRepository = getBean(CustomerProfileRepository.class);
String levelId = customerProfileRepository.findLevelId(325);
Related Concepts¶
- [[JPA]]
- Spring Framework
- [[Repository pattern]]
- [[Dependency injection]]
Sources¶
^[600-developer__java__application-server__weblogic__weblogic-spring-jpa.md]