Skip to content

Reuse component scan metadata when parsing scanned configuration candidates #37739

Open

Description

@gregjotau

During @ComponentScan, ScannedGenericBeanDefinition already holds the candidate's annotation metadata. When ConfigurationClassParser encounters that definition, it looks up the class by name and can parse the same class file again under a different resource key.

The attached patch uses the scanner's metadata and resource for that parse. It keeps the existing fallback and leaves the metadata cache unchanged. This is narrower than the class-name cache proposed in #36977.

In an annotation-only context with 1,200 components and 600 non-components, three fresh JDK 27 JVMs per variant gave these median measurements for spring.context.config-classes.parse:

Baseline Patched
Startup-thread CPU 156 ms 97 ms
Startup-thread allocation 121 MiB 62 MiB

All runs registered the same 1,209 bean definitions. I measured thread CPU time and allocated bytes at the boundaries of the Spring startup step using ThreadMXBean. The included regression test fails on upstream main and passes with the patch. ./gradlew :spring-context:check passes on JDK 25.

Maintainers are welcome to apply or adapt the patch and merge it directly. No attribution is needed.

Ready-to-apply patch

Save the block as a file and apply it with git apply. The patch is based on a85686e.

diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
index 54a9186..b2c8ff6 100644
--- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
+++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
@@ -52,10 +52,12 @@ import org.springframework.core.annotation.AnnotationUtils;
 import org.springframework.core.annotation.MergedAnnotation;
 import org.springframework.core.env.ConfigurableEnvironment;
 import org.springframework.core.env.Environment;
+import org.springframework.core.io.Resource;
 import org.springframework.core.io.ResourceLoader;
 import org.springframework.core.io.support.PropertySourceDescriptor;
 import org.springframework.core.io.support.PropertySourceProcessor;
 import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.ClassMetadata;
 import org.springframework.core.type.MethodMetadata;
 import org.springframework.core.type.StandardAnnotationMetadata;
 import org.springframework.core.type.classreading.MetadataReader;
@@ -202,6 +204,22 @@ class ConfigurationClassParser {
 		return configClass;
 	}
 
+	private void parseScannedCandidate(BeanDefinition candidate, String beanName) throws IOException {
+		String className = candidate.getBeanClassName();
+		if (candidate instanceof ScannedGenericBeanDefinition scanned && className != null &&
+				!className.startsWith("java") && !DEFAULT_EXCLUSION_FILTER.test(className)) {
+			Resource resource = scanned.getResource();
+			if (resource != null) {
+				MetadataReader reader = new ScannedMetadataReader(scanned.getMetadata(), resource);
+				ConfigurationClass configClass = new ConfigurationClass(reader, beanName);
+				processConfigurationClass(configClass, DEFAULT_EXCLUSION_FILTER, new SourceClass(reader));
+				return;
+			}
+		}
+		parse(className, beanName);
+	}
+
+
 	final ConfigurationClass parse(@Nullable String className, String beanName) throws IOException {
 		Assert.notNull(className, "No bean class name for configuration class bean definition");
 		MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
@@ -235,6 +253,11 @@ class ConfigurationClassParser {
 
 
 	protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) {
+		processConfigurationClass(configClass, filter, null);
+	}
+
+	private void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter,
+			@Nullable SourceClass initialSource) {
 		if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
 			return;
 		}
@@ -269,7 +292,7 @@ class ConfigurationClassParser {
 		// Recursively process the configuration class and its superclass hierarchy.
 		SourceClass sourceClass = null;
 		try {
-			sourceClass = asSourceClass(configClass, filter);
+			sourceClass = (initialSource != null ? initialSource : asSourceClass(configClass, filter));
 			do {
 				sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
 			}
@@ -343,7 +366,7 @@ class ConfigurationClassParser {
 						bdCand = holder.getBeanDefinition();
 					}
 					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
-						parse(bdCand.getBeanClassName(), holder.getBeanName());
+						parseScannedCandidate(bdCand, holder.getBeanName());
 					}
 				}
 			}
@@ -956,6 +979,25 @@ class ConfigurationClassParser {
 	}
 
 
+	private record ScannedMetadataReader(AnnotationMetadata metadata, Resource resource) implements MetadataReader {
+
+		@Override
+		public ClassMetadata getClassMetadata() {
+			return this.metadata;
+		}
+
+		@Override
+		public AnnotationMetadata getAnnotationMetadata() {
+			return this.metadata;
+		}
+
+		@Override
+		public Resource getResource() {
+			return this.resource;
+		}
+	}
+
+
 	/**
 	 * Simple wrapper that allows annotated source classes to be dealt with
 	 * in a uniform manner, regardless of how they are loaded.
diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java
index a8190b5..017b8ac 100644
--- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java
+++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java
@@ -5,10 +5,13 @@
 
 package org.springframework.context.annotation;
 
+import java.io.IOException;
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
+import java.util.ArrayList;
+import java.util.List;
 import java.util.Set;
 
 import example.scannable.CustomComponent;
@@ -48,6 +51,7 @@ import org.springframework.core.env.ConfigurableEnvironment;
 import org.springframework.core.env.Environment;
 import org.springframework.core.io.ResourceLoader;
 import org.springframework.core.testfixture.io.SerializationTestUtils;
+import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
 import org.springframework.core.type.classreading.MetadataReader;
 import org.springframework.core.type.classreading.MetadataReaderFactory;
 import org.springframework.core.type.filter.TypeFilter;
@@ -97,6 +101,30 @@ class ComponentScanAnnotationIntegrationTests {
 				"AnnotationConfigApplicationContext did not trigger component scanning as expected").isTrue();
 	}
 
+	@Test
+	void reusesMetadataFromComponentScan() {
+		List<String> classNameLookups = new ArrayList<>();
+		try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
+			ConfigurationClassPostProcessor processor = new ConfigurationClassPostProcessor();
+			processor.setEnvironment(context.getEnvironment());
+			processor.setResourceLoader(context);
+			processor.setMetadataReaderFactory(new CachingMetadataReaderFactory(context) {
+				@Override
+				public MetadataReader getMetadataReader(String className) throws IOException {
+					classNameLookups.add(className);
+					return super.getMetadataReader(className);
+				}
+			});
+			context.getBeanFactory().registerSingleton(
+					AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME, processor);
+			context.register(ComponentScanAnnotatedConfig.class);
+			context.refresh();
+
+			assertThat(context.getBean(FooServiceImpl.class)).isNotNull();
+			assertThat(classNameLookups).doesNotContain(FooServiceImpl.class.getName());
+		}
+	}
+
 	@Test
 	void viaContextRegistration_WithValueAttribute() {
 		ApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanAnnotatedConfig_WithValueAttribute.class);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions