Skip to content

Commit 1458d5f

Browse files
committed
Add support for @transactional in native images
This commit introduces a TransactionBeanRegistrationAotProcessor in charge of creating the required proxy and reflection hints when @transactional is detected on beans. It also refines DefaultAopProxyFactory to throw an exception when a subclass-based proxy is created in native images since that's unsupported for now (see gh-28115 related issue). Closes gh-28717
1 parent a64d371 commit 1458d5f

File tree

5 files changed

+283
-2
lines changed

5 files changed

+283
-2
lines changed

spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
5454

5555
@Override
5656
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
57-
if (!NativeDetector.inNativeImage() &&
58-
(config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
57+
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
5958
Class<?> targetClass = config.getTargetClass();
6059
if (targetClass == null) {
6160
throw new AopConfigException("TargetSource cannot determine target class: " +
@@ -64,6 +63,9 @@ public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException
6463
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) {
6564
return new JdkDynamicAopProxy(config);
6665
}
66+
if (NativeDetector.inNativeImage()) {
67+
throw new AopConfigException("Subclass-based proxies are not support yet in native images");
68+
}
6769
return new ObjenesisCglibAopProxy(config);
6870
}
6971
else {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*
2+
* Copyright 2002-2022 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.transaction.annotation;
18+
19+
import java.lang.reflect.AnnotatedElement;
20+
import java.util.LinkedHashSet;
21+
import java.util.Set;
22+
23+
import org.springframework.aop.SpringProxy;
24+
import org.springframework.aop.framework.Advised;
25+
import org.springframework.aot.generate.GenerationContext;
26+
import org.springframework.aot.hint.MemberCategory;
27+
import org.springframework.aot.hint.RuntimeHints;
28+
import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
29+
import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
30+
import org.springframework.beans.factory.aot.BeanRegistrationCode;
31+
import org.springframework.beans.factory.support.RegisteredBean;
32+
import org.springframework.core.DecoratingProxy;
33+
import org.springframework.core.annotation.MergedAnnotations;
34+
import org.springframework.util.ClassUtils;
35+
import org.springframework.util.ReflectionUtils;
36+
37+
/**
38+
* AOT {@code BeanRegistrationAotProcessor} that detects the presence of
39+
* {@link Transactional @Transactional} on annotated elements and creates
40+
* the required proxy and reflection hints.
41+
*
42+
* @author Sebastien Deleuze
43+
* @since 6.0
44+
* @see TransactionRuntimeHintsRegistrar
45+
*/
46+
public class TransactionBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor {
47+
48+
private final static String JAKARTA_TRANSACTIONAL_CLASS_NAME = "jakarta.transaction.Transactional";
49+
50+
@Override
51+
public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
52+
Class<?> beanClass = registeredBean.getBeanClass();
53+
if (isTransactional(beanClass)) {
54+
return new TransactionBeanRegistrationAotContribution(beanClass);
55+
}
56+
return null;
57+
}
58+
59+
private boolean isTransactional(Class<?> beanClass) {
60+
Set<AnnotatedElement> elements = new LinkedHashSet<>();
61+
elements.add(beanClass);
62+
ReflectionUtils.doWithMethods(beanClass, elements::add);
63+
for (Class<?> interfaceClass : ClassUtils.getAllInterfacesForClass(beanClass)) {
64+
elements.add(interfaceClass);
65+
ReflectionUtils.doWithMethods(interfaceClass, elements::add);
66+
}
67+
return elements.stream().anyMatch(element -> {
68+
MergedAnnotations mergedAnnotations = MergedAnnotations.from(element, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY);
69+
return mergedAnnotations.isPresent(Transactional.class) || mergedAnnotations.isPresent(JAKARTA_TRANSACTIONAL_CLASS_NAME);
70+
});
71+
}
72+
73+
private static class TransactionBeanRegistrationAotContribution implements BeanRegistrationAotContribution {
74+
75+
private Class<?> beanClass;
76+
77+
public TransactionBeanRegistrationAotContribution(Class<?> beanClass) {
78+
this.beanClass = beanClass;
79+
}
80+
81+
@Override
82+
public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) {
83+
RuntimeHints runtimeHints = generationContext.getRuntimeHints();
84+
LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<>();
85+
Class<?>[] proxyInterfaces = ClassUtils.getAllInterfacesForClass(this.beanClass);
86+
if (proxyInterfaces.length == 0) {
87+
return;
88+
}
89+
for (Class<?> proxyInterface : proxyInterfaces) {
90+
interfaces.add(proxyInterface);
91+
runtimeHints.reflection().registerType(proxyInterface, builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
92+
}
93+
interfaces.add(SpringProxy.class);
94+
interfaces.add(Advised.class);
95+
interfaces.add(DecoratingProxy.class);
96+
runtimeHints.proxies().registerJdkProxy(interfaces.toArray(Class[]::new));
97+
}
98+
}
99+
}

spring-tx/src/main/java/org/springframework/transaction/annotation/TransactionRuntimeHintsRegistrar.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
*
3131
* @author Sebastien Deleuze
3232
* @since 6.0
33+
* @see TransactionBeanRegistrationAotProcessor
3334
*/
3435
public class TransactionRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
3536

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
org.springframework.beans.factory.aot.BeanRegistrationAotProcessor=\
2+
org.springframework.transaction.annotation.TransactionBeanRegistrationAotProcessor
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/*
2+
* Copyright 2002-2022 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.transaction.annotation;
18+
19+
import org.junit.jupiter.api.Test;
20+
21+
import org.springframework.aop.SpringProxy;
22+
import org.springframework.aop.framework.Advised;
23+
import org.springframework.aot.generate.GenerationContext;
24+
import org.springframework.aot.hint.MemberCategory;
25+
import org.springframework.aot.hint.RuntimeHintsPredicates;
26+
import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
27+
import org.springframework.beans.factory.aot.BeanRegistrationCode;
28+
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
29+
import org.springframework.beans.factory.support.RegisteredBean;
30+
import org.springframework.beans.factory.support.RootBeanDefinition;
31+
import org.springframework.core.DecoratingProxy;
32+
import org.springframework.core.testfixture.aot.generate.TestGenerationContext;
33+
import org.springframework.lang.Nullable;
34+
35+
import static org.assertj.core.api.Assertions.assertThat;
36+
import static org.mockito.Mockito.mock;
37+
38+
/**
39+
* Tests for {@link TransactionBeanRegistrationAotProcessor}.
40+
*
41+
* @author Sebastien Deleuze
42+
*/
43+
public class TransactionBeanRegistrationAotProcessorTests {
44+
45+
private final TransactionBeanRegistrationAotProcessor processor = new TransactionBeanRegistrationAotProcessor();
46+
47+
private final GenerationContext generationContext = new TestGenerationContext();
48+
49+
@Test
50+
void shouldSkipNonAnnotatedType() {
51+
process(NonAnnotatedBean.class);
52+
assertThat(this.generationContext.getRuntimeHints().reflection().typeHints()).isEmpty();
53+
assertThat(this.generationContext.getRuntimeHints().proxies().jdkProxies()).isEmpty();
54+
}
55+
56+
@Test
57+
void shouldSkipAnnotatedTypeWithNoInterface() {
58+
process(NoInterfaceBean.class);
59+
assertThat(this.generationContext.getRuntimeHints().reflection().typeHints()).isEmpty();
60+
assertThat(this.generationContext.getRuntimeHints().proxies().jdkProxies()).isEmpty();
61+
}
62+
63+
@Test
64+
void shouldProcessTransactionalOnClass() {
65+
process(TransactionalOnTypeBean.class);
66+
assertThat(RuntimeHintsPredicates.reflection().onType(NonAnnotatedTransactionalInterface.class)
67+
.withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.generationContext.getRuntimeHints());
68+
assertThat(RuntimeHintsPredicates.proxies().forInterfaces(NonAnnotatedTransactionalInterface.class, SpringProxy.class, Advised.class, DecoratingProxy.class)).accepts(this.generationContext.getRuntimeHints());
69+
}
70+
71+
@Test
72+
void shouldProcessJakartaTransactionalOnClass() {
73+
process(JakartaTransactionalOnTypeBean.class);
74+
assertThat(RuntimeHintsPredicates.reflection().onType(NonAnnotatedTransactionalInterface.class)
75+
.withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.generationContext.getRuntimeHints());
76+
assertThat(RuntimeHintsPredicates.proxies().forInterfaces(NonAnnotatedTransactionalInterface.class, SpringProxy.class, Advised.class, DecoratingProxy.class)).accepts(this.generationContext.getRuntimeHints());
77+
}
78+
79+
@Test
80+
void shouldProcessTransactionalOnInterface() {
81+
process(TransactionalOnTypeInterface.class);
82+
assertThat(RuntimeHintsPredicates.reflection().onType(TransactionalOnTypeInterface.class)
83+
.withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.generationContext.getRuntimeHints());
84+
assertThat(RuntimeHintsPredicates.proxies().forInterfaces(TransactionalOnTypeInterface.class, SpringProxy.class, Advised.class, DecoratingProxy.class)).accepts(this.generationContext.getRuntimeHints());
85+
}
86+
87+
@Test
88+
void shouldProcessTransactionalOnClassMethod() {
89+
process(TransactionalOnClassMethodBean.class);
90+
assertThat(RuntimeHintsPredicates.reflection().onType(NonAnnotatedTransactionalInterface.class)
91+
.withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.generationContext.getRuntimeHints());
92+
assertThat(RuntimeHintsPredicates.proxies().forInterfaces(NonAnnotatedTransactionalInterface.class, SpringProxy.class, Advised.class, DecoratingProxy.class)).accepts(this.generationContext.getRuntimeHints());
93+
}
94+
95+
@Test
96+
void shouldProcessTransactionalOnInterfaceMethod() {
97+
process(TransactionalOnInterfaceMethodBean.class);
98+
assertThat(RuntimeHintsPredicates.reflection().onType(TransactionalOnMethodInterface.class)
99+
.withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.generationContext.getRuntimeHints());
100+
assertThat(RuntimeHintsPredicates.proxies().forInterfaces(TransactionalOnMethodInterface.class, SpringProxy.class, Advised.class, DecoratingProxy.class)).accepts(this.generationContext.getRuntimeHints());
101+
}
102+
103+
private void process(Class<?> beanClass) {
104+
BeanRegistrationAotContribution contribution = createContribution(beanClass);
105+
if (contribution != null) {
106+
contribution.applyTo(this.generationContext, mock(BeanRegistrationCode.class));
107+
}
108+
}
109+
110+
@Nullable
111+
private BeanRegistrationAotContribution createContribution(Class<?> beanClass) {
112+
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
113+
beanFactory.registerBeanDefinition(beanClass.getName(), new RootBeanDefinition(beanClass));
114+
return this.processor.processAheadOfTime(RegisteredBean.of(beanFactory, beanClass.getName()));
115+
}
116+
117+
118+
@SuppressWarnings("unused")
119+
static class NonAnnotatedBean {
120+
121+
public void notTransactional() {
122+
}
123+
}
124+
125+
@SuppressWarnings("unused")
126+
@Transactional
127+
static class NoInterfaceBean {
128+
129+
public void notTransactional() {
130+
}
131+
}
132+
133+
@Transactional
134+
static class TransactionalOnTypeBean implements NonAnnotatedTransactionalInterface {
135+
136+
public void transactional() {
137+
}
138+
}
139+
140+
@jakarta.transaction.Transactional
141+
static class JakartaTransactionalOnTypeBean implements NonAnnotatedTransactionalInterface {
142+
143+
public void transactional() {
144+
}
145+
}
146+
147+
interface NonAnnotatedTransactionalInterface {
148+
149+
void transactional();
150+
}
151+
152+
@Transactional
153+
interface TransactionalOnTypeInterface {
154+
155+
void transactional();
156+
}
157+
158+
static class TransactionalOnClassMethodBean implements NonAnnotatedTransactionalInterface {
159+
160+
@Transactional
161+
public void transactional() {
162+
}
163+
}
164+
165+
interface TransactionalOnMethodInterface {
166+
167+
@Transactional
168+
void transactional();
169+
}
170+
171+
static class TransactionalOnInterfaceMethodBean implements TransactionalOnMethodInterface {
172+
173+
@Transactional
174+
public void transactional() {
175+
}
176+
}
177+
}

0 commit comments

Comments
 (0)