Skip to content

Commit fb423d6

Browse files
committed
Add ClassFile variant for class metadata reading
Prior to this commit, Spring Framework would use its own ASM fork to read class/method/annotation metadata from bytecode. This is typically used in configuration class parsing to build bean definitions without actually loading classes at runtime at that step. This commit adds support for a new metadata reading implementation that uses the ClassFile API available as of Java 24. For now, this is turned on by default for Java 24+. Closes gh-33616
1 parent 20b35f0 commit fb423d6

File tree

13 files changed

+1326
-294
lines changed

13 files changed

+1326
-294
lines changed

spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@
8484
import org.springframework.core.type.AnnotationMetadata;
8585
import org.springframework.core.type.MethodMetadata;
8686
import org.springframework.core.type.classreading.MetadataReaderFactory;
87-
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
8887
import org.springframework.javapoet.ClassName;
8988
import org.springframework.javapoet.CodeBlock;
9089
import org.springframework.util.Assert;
@@ -271,7 +270,7 @@ public void setBeanFactory(BeanFactory beanFactory) {
271270
"AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory: " + beanFactory);
272271
}
273272
this.beanFactory = clbf;
274-
this.metadataReaderFactory = new SimpleMetadataReaderFactory(clbf.getBeanClassLoader());
273+
this.metadataReaderFactory = MetadataReaderFactory.create(clbf.getBeanClassLoader());
275274
}
276275

277276

spring-core/spring-core.gradle

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ apply plugin: "kotlin"
1111
apply plugin: "kotlinx-serialization"
1212

1313
multiRelease {
14-
releaseVersions 21
14+
releaseVersions 21, 24
1515
}
1616

1717
def javapoetVersion = "1.13.0"
@@ -20,6 +20,7 @@ def objenesisVersion = "3.4"
2020
configurations {
2121
java21Api.extendsFrom(api)
2222
java21Implementation.extendsFrom(implementation)
23+
java24Api.extendsFrom(api)
2324
javapoet
2425
objenesis
2526
graalvm

spring-core/src/main/java/org/springframework/core/type/classreading/CachingMetadataReaderFactory.java

+14-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2022 the original author or authors.
2+
* Copyright 2002-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -36,11 +36,13 @@
3636
* @author Costin Leau
3737
* @since 2.5
3838
*/
39-
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
39+
public class CachingMetadataReaderFactory implements MetadataReaderFactory {
4040

4141
/** Default maximum number of entries for a local MetadataReader cache: 256. */
4242
public static final int DEFAULT_CACHE_LIMIT = 256;
4343

44+
private final MetadataReaderFactory delegate;
45+
4446
/** MetadataReader cache: either local or shared at the ResourceLoader level. */
4547
private @Nullable Map<Resource, MetadataReader> metadataReaderCache;
4648

@@ -50,7 +52,7 @@ public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
5052
* using a local resource cache.
5153
*/
5254
public CachingMetadataReaderFactory() {
53-
super();
55+
this.delegate = MetadataReaderFactory.create((ClassLoader) null);
5456
setCacheLimit(DEFAULT_CACHE_LIMIT);
5557
}
5658

@@ -60,7 +62,7 @@ public CachingMetadataReaderFactory() {
6062
* @param classLoader the ClassLoader to use
6163
*/
6264
public CachingMetadataReaderFactory(@Nullable ClassLoader classLoader) {
63-
super(classLoader);
65+
this.delegate = MetadataReaderFactory.create(classLoader);
6466
setCacheLimit(DEFAULT_CACHE_LIMIT);
6567
}
6668

@@ -72,7 +74,7 @@ public CachingMetadataReaderFactory(@Nullable ClassLoader classLoader) {
7274
* @see DefaultResourceLoader#getResourceCache
7375
*/
7476
public CachingMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
75-
super(resourceLoader);
77+
this.delegate = MetadataReaderFactory.create(resourceLoader);
7678
if (resourceLoader instanceof DefaultResourceLoader defaultResourceLoader) {
7779
this.metadataReaderCache = defaultResourceLoader.getResourceCache(MetadataReader.class);
7880
}
@@ -81,7 +83,6 @@ public CachingMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
8183
}
8284
}
8385

84-
8586
/**
8687
* Specify the maximum number of entries for the MetadataReader cache.
8788
* <p>Default is 256 for a local cache, whereas a shared cache is
@@ -112,14 +113,18 @@ public int getCacheLimit() {
112113
}
113114
}
114115

116+
@Override
117+
public MetadataReader getMetadataReader(String className) throws IOException {
118+
return this.delegate.getMetadataReader(className);
119+
}
115120

116121
@Override
117122
public MetadataReader getMetadataReader(Resource resource) throws IOException {
118123
if (this.metadataReaderCache instanceof ConcurrentMap) {
119124
// No synchronization necessary...
120125
MetadataReader metadataReader = this.metadataReaderCache.get(resource);
121126
if (metadataReader == null) {
122-
metadataReader = super.getMetadataReader(resource);
127+
metadataReader = this.delegate.getMetadataReader(resource);
123128
this.metadataReaderCache.put(resource, metadataReader);
124129
}
125130
return metadataReader;
@@ -128,14 +133,14 @@ else if (this.metadataReaderCache != null) {
128133
synchronized (this.metadataReaderCache) {
129134
MetadataReader metadataReader = this.metadataReaderCache.get(resource);
130135
if (metadataReader == null) {
131-
metadataReader = super.getMetadataReader(resource);
136+
metadataReader = this.delegate.getMetadataReader(resource);
132137
this.metadataReaderCache.put(resource, metadataReader);
133138
}
134139
return metadataReader;
135140
}
136141
}
137142
else {
138-
return super.getMetadataReader(resource);
143+
return this.delegate.getMetadataReader(resource);
139144
}
140145
}
141146

spring-core/src/main/java/org/springframework/core/type/classreading/MetadataReaderFactory.java

+24-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -18,13 +18,17 @@
1818

1919
import java.io.IOException;
2020

21+
import org.jspecify.annotations.Nullable;
22+
2123
import org.springframework.core.io.Resource;
24+
import org.springframework.core.io.ResourceLoader;
2225

2326
/**
2427
* Factory interface for {@link MetadataReader} instances.
2528
* Allows for caching a MetadataReader per original resource.
2629
*
2730
* @author Juergen Hoeller
31+
* @author Brian Clozel
2832
* @since 2.5
2933
* @see SimpleMetadataReaderFactory
3034
* @see CachingMetadataReaderFactory
@@ -49,4 +53,23 @@ public interface MetadataReaderFactory {
4953
*/
5054
MetadataReader getMetadataReader(Resource resource) throws IOException;
5155

56+
/**
57+
* Create a default {@link MetadataReaderFactory} implementation that's suitable
58+
* for the current JVM.
59+
* @return a new factory instance
60+
* @since 7.0
61+
*/
62+
static MetadataReaderFactory create(@Nullable ResourceLoader resourceLoader) {
63+
return MetadataReaderFactoryDelegate.create(resourceLoader);
64+
}
65+
66+
/**
67+
* Create a default {@link MetadataReaderFactory} implementation that's suitable
68+
* for the current JVM.
69+
* @return a new factory instance
70+
* @since 7.0
71+
*/
72+
static MetadataReaderFactory create(@Nullable ClassLoader classLoader) {
73+
return MetadataReaderFactoryDelegate.create(classLoader);
74+
}
5275
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright 2002-2025 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.core.type.classreading;
18+
19+
import org.jspecify.annotations.Nullable;
20+
21+
import org.springframework.core.io.ResourceLoader;
22+
23+
/**
24+
* Internal delegate for instantiating {@link MetadataReaderFactory} implementations.
25+
* For JDK < 24, the {@link SimpleMetadataReaderFactory} is being used.
26+
*
27+
* @author Brian Clozel
28+
* @since 7.0
29+
* @see MetadataReaderFactory
30+
*/
31+
abstract class MetadataReaderFactoryDelegate {
32+
33+
static MetadataReaderFactory create(@Nullable ResourceLoader resourceLoader) {
34+
return new SimpleMetadataReaderFactory(resourceLoader);
35+
}
36+
37+
static MetadataReaderFactory create(@Nullable ClassLoader classLoader) {
38+
return new SimpleMetadataReaderFactory(classLoader);
39+
}
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
/*
2+
* Copyright 2002-2025 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.core.type.classreading;
18+
19+
20+
import java.lang.classfile.Annotation;
21+
import java.lang.classfile.AnnotationElement;
22+
import java.lang.classfile.AnnotationValue;
23+
import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute;
24+
import java.lang.reflect.Array;
25+
import java.util.Collections;
26+
import java.util.LinkedHashMap;
27+
import java.util.Map;
28+
import java.util.Objects;
29+
import java.util.Set;
30+
import java.util.stream.Collectors;
31+
import java.util.stream.Stream;
32+
33+
import org.jspecify.annotations.Nullable;
34+
35+
import org.springframework.core.annotation.AnnotationFilter;
36+
import org.springframework.core.annotation.MergedAnnotation;
37+
import org.springframework.core.annotation.MergedAnnotations;
38+
import org.springframework.util.ClassUtils;
39+
40+
/**
41+
* Parse {@link RuntimeVisibleAnnotationsAttribute} into {@link MergedAnnotations}
42+
* instances.
43+
* @author Brian Clozel
44+
*/
45+
abstract class ClassFileAnnotationMetadata {
46+
47+
static MergedAnnotations createMergedAnnotations(String className, RuntimeVisibleAnnotationsAttribute annotationAttribute, @Nullable ClassLoader classLoader) {
48+
Set<MergedAnnotation<?>> annotations = annotationAttribute.annotations()
49+
.stream()
50+
.map(ann -> createMergedAnnotation(className, ann, classLoader))
51+
.filter(Objects::nonNull)
52+
.collect(Collectors.toSet());
53+
return MergedAnnotations.of(annotations);
54+
}
55+
56+
@SuppressWarnings("unchecked")
57+
private static <A extends java.lang.annotation.Annotation> @Nullable MergedAnnotation<A> createMergedAnnotation(String className, Annotation annotation, @Nullable ClassLoader classLoader) {
58+
String typeName = fromTypeDescriptor(annotation.className().stringValue());
59+
if (AnnotationFilter.PLAIN.matches(typeName)) {
60+
return null;
61+
}
62+
Map<String, Object> attributes = new LinkedHashMap<>(4);
63+
try {
64+
for (AnnotationElement element : annotation.elements()) {
65+
Object annotationValue = readAnnotationValue(className, element.value(), classLoader);
66+
if (annotationValue != null) {
67+
attributes.put(element.name().stringValue(), annotationValue);
68+
}
69+
}
70+
Map<String, Object> compactedAttributes = (attributes.isEmpty() ? Collections.emptyMap() : attributes);
71+
Class<A> annotationType = (Class<A>) ClassUtils.forName(typeName, classLoader);
72+
return MergedAnnotation.of(classLoader, new Source(annotation), annotationType, compactedAttributes);
73+
}
74+
catch (ClassNotFoundException | LinkageError ex) {
75+
return null;
76+
}
77+
}
78+
79+
private static @Nullable Object readAnnotationValue(String className, AnnotationValue elementValue, @Nullable ClassLoader classLoader) {
80+
switch (elementValue) {
81+
case AnnotationValue.OfConstant constantValue -> {
82+
return constantValue.resolvedValue();
83+
}
84+
case AnnotationValue.OfAnnotation annotationValue -> {
85+
return createMergedAnnotation(className, annotationValue.annotation(), classLoader);
86+
}
87+
case AnnotationValue.OfClass classValue -> {
88+
return fromTypeDescriptor(classValue.className().stringValue());
89+
}
90+
case AnnotationValue.OfEnum enumValue -> {
91+
return parseEnum(enumValue, classLoader);
92+
}
93+
case AnnotationValue.OfArray arrayValue -> {
94+
return parseArrayValue(className, classLoader, arrayValue);
95+
}
96+
}
97+
}
98+
99+
private static String fromTypeDescriptor(String descriptor) {
100+
return descriptor.substring(1, descriptor.length() - 1)
101+
.replace('/', '.');
102+
}
103+
104+
private static Object parseArrayValue(String className, @org.jetbrains.annotations.Nullable ClassLoader classLoader, AnnotationValue.OfArray arrayValue) {
105+
if (arrayValue.values().isEmpty()) {
106+
return new Object[0];
107+
}
108+
Stream<AnnotationValue> stream = arrayValue.values().stream();
109+
switch (arrayValue.values().getFirst()) {
110+
case AnnotationValue.OfInt _ -> {
111+
return stream.map(AnnotationValue.OfInt.class::cast).mapToInt(AnnotationValue.OfInt::intValue).toArray();
112+
}
113+
case AnnotationValue.OfDouble _ -> {
114+
return stream.map(AnnotationValue.OfDouble.class::cast).mapToDouble(AnnotationValue.OfDouble::doubleValue).toArray();
115+
}
116+
case AnnotationValue.OfLong _ -> {
117+
return stream.map(AnnotationValue.OfLong.class::cast).mapToLong(AnnotationValue.OfLong::longValue).toArray();
118+
}
119+
default -> {
120+
Object firstResolvedValue = readAnnotationValue(className, arrayValue.values().getFirst(), classLoader);
121+
return stream
122+
.map(rawValue -> readAnnotationValue(className, rawValue, classLoader))
123+
.toArray(s -> (Object[]) Array.newInstance(firstResolvedValue.getClass(), s));
124+
}
125+
}
126+
}
127+
128+
@SuppressWarnings("unchecked")
129+
private static @Nullable <E extends Enum<E>> Enum<E> parseEnum(AnnotationValue.OfEnum enumValue, @Nullable ClassLoader classLoader) {
130+
String enumClassName = fromTypeDescriptor(enumValue.className().stringValue());
131+
try {
132+
Class<E> enumClass = (Class<E>) ClassUtils.forName(enumClassName, classLoader);
133+
return Enum.valueOf(enumClass, enumValue.constantName().stringValue());
134+
}
135+
catch (ClassNotFoundException | LinkageError ex) {
136+
return null;
137+
}
138+
}
139+
140+
record Source(Annotation entryName) {
141+
142+
}
143+
144+
}

0 commit comments

Comments
 (0)