Handle injection of several persistence units

This commit adapts the generated code so that each injection point has
a dedicated namespace in the form of a private method. That prevents
the same variable to be reused twice which lead to a compilation failure
previously.

Closes gh-30437
This commit is contained in:
Stephane Nicoll
2023-05-10 13:43:26 +02:00
parent bd66c70b2b
commit 120c228b70
2 changed files with 75 additions and 11 deletions

View File

@@ -32,6 +32,7 @@ import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.FieldHint;
import org.springframework.aot.hint.TypeReference;
import org.springframework.aot.test.generate.TestGenerationContext;
import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
@@ -160,6 +161,28 @@ class PersistenceAnnotationBeanPostProcessorAotContributionTests {
});
}
@Test
void processAheadOfTimeWhenPersistenceContextOnPrivateFields() {
RegisteredBean registeredBean = registerBean(
SeveralPersistenceContextField.class);
testCompile(registeredBean, (actual, compiled) -> {
EntityManagerFactory entityManagerFactory = mock();
this.beanFactory.registerSingleton("custom", entityManagerFactory);
this.beanFactory.registerAlias("custom", "another");
SeveralPersistenceContextField instance = new SeveralPersistenceContextField();
actual.accept(registeredBean, instance);
assertThat(instance).extracting("customEntityManager").isNotNull();
assertThat(instance).extracting("anotherEntityManager").isNotNull();
assertThat(this.generationContext.getRuntimeHints().reflection().typeHints())
.singleElement().satisfies(typeHint -> {
assertThat(typeHint.getType()).isEqualTo(
TypeReference.of(SeveralPersistenceContextField.class));
assertThat(typeHint.fields().map(FieldHint::getName))
.containsOnly("customEntityManager", "anotherEntityManager");
});
});
}
private RegisteredBean registerBean(Class<?> beanClass) {
String beanName = "testBean";
this.beanFactory.registerBeanDefinition(beanName,
@@ -256,4 +279,16 @@ class PersistenceAnnotationBeanPostProcessorAotContributionTests {
}
static class SeveralPersistenceContextField {
@SuppressWarnings("unused")
@PersistenceContext(name = "custom")
private EntityManager customEntityManager;
@SuppressWarnings("unused")
@PersistenceContext(name = "another")
private EntityManager anotherEntityManager;
}
}