Skip to content

Commit e9616b7

Browse files
philwebbcbeams
authored andcommitted
Backport "Prevent duplicate @import processing"
Refactor ConfigurationClassParser to recursively find values from all @import annotations, combining them into a single unique set. This change prevents ImportBeanDefinitionRegistrars from being invoked twice. Issue: SPR-9925 Backport-Commit: 6d8b37d Conflicts: spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
1 parent bbd5fc6 commit e9616b7

File tree

2 files changed

+84
-43
lines changed

2 files changed

+84
-43
lines changed

org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java

Lines changed: 31 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,13 @@
1717
package org.springframework.context.annotation;
1818

1919
import java.io.IOException;
20-
import java.lang.annotation.Annotation;
21-
import java.util.ArrayList;
20+
import java.util.Arrays;
2221
import java.util.Collections;
2322
import java.util.Comparator;
2423
import java.util.HashMap;
24+
import java.util.HashSet;
2525
import java.util.Iterator;
2626
import java.util.LinkedHashSet;
27-
import java.util.List;
2827
import java.util.Map;
2928
import java.util.Set;
3029
import java.util.Stack;
@@ -221,10 +220,9 @@ protected AnnotationMetadata doProcessConfigurationClass(
221220
}
222221

223222
// process any @Import annotations
224-
List<AnnotationAttributes> imports =
225-
findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
226-
for (AnnotationAttributes importAnno : imports) {
227-
processImport(configClass, importAnno.getStringArray("value"), true);
223+
Set<String> imports = getImports(metadata.getClassName(), null, new HashSet<String>());
224+
if (imports != null && !imports.isEmpty()) {
225+
processImport(configClass, imports.toArray(new String[imports.size()]), true);
228226
}
229227

230228
// process any @ImportResource annotations
@@ -274,45 +272,36 @@ else if (superclass.startsWith("java")) {
274272
}
275273

276274
/**
277-
* Return a list of attribute maps for all declarations of the given annotation
278-
* on the given annotated class using the given MetadataReaderFactory to introspect
279-
* annotation metadata. Meta-annotations are ordered first in the list, and if the
280-
* target annotation is declared directly on the class, its map of attributes will be
281-
* ordered last in the list.
282-
* @param targetAnnotation the annotation to search for, both locally and as a meta-annotation
283-
* @param annotatedClassName the class to inspect
284-
* @param classValuesAsString whether class attributes should be returned as strings
275+
* Recursively collect all declared {@code @Import} values. Unlike most
276+
* meta-annotations it is valid to have several {@code @Import}s declared with
277+
* different values, the usual process or returning values from the first
278+
* meta-annotation on a class is not sufficient.
279+
* <p>For example, it is common for a {@code @Configuration} class to declare direct
280+
* {@code @Import}s in addition to meta-imports originating from an {@code @Enable}
281+
* annotation.
282+
* @param className the class name to search
283+
* @param imports the imports collected so far or {@code null}
284+
* @param visited used to track visited classes to prevent infinite recursion (must not be null)
285+
* @return a set of all {@link Import#value() import values} or {@code null}
286+
* @throws IOException if there is any problem reading metadata from the named class
285287
*/
286-
private List<AnnotationAttributes> findAllAnnotationAttributes(
287-
Class<? extends Annotation> targetAnnotation, String annotatedClassName,
288-
boolean classValuesAsString) throws IOException {
289-
290-
List<AnnotationAttributes> allAttribs = new ArrayList<AnnotationAttributes>();
291-
292-
MetadataReader reader = this.metadataReaderFactory.getMetadataReader(annotatedClassName);
293-
AnnotationMetadata metadata = reader.getAnnotationMetadata();
294-
String targetAnnotationType = targetAnnotation.getName();
295-
296-
for (String annotationType : metadata.getAnnotationTypes()) {
297-
if (annotationType.equals(targetAnnotationType)) {
298-
continue;
288+
private Set<String> getImports(String className, Set<String> imports,
289+
Set<String> visited) throws IOException {
290+
if (visited.add(className)) {
291+
AnnotationMetadata metadata = metadataReaderFactory.getMetadataReader(className).getAnnotationMetadata();
292+
Map<String, Object> attributes = metadata.getAnnotationAttributes(Import.class.getName(), true);
293+
if (attributes != null) {
294+
String[] value = (String[]) attributes.get("value");
295+
if (value != null && value.length > 0) {
296+
imports = (imports == null ? new LinkedHashSet<String>() : imports);
297+
imports.addAll(Arrays.asList(value));
298+
}
299299
}
300-
AnnotationMetadata metaAnnotations =
301-
this.metadataReaderFactory.getMetadataReader(annotationType).getAnnotationMetadata();
302-
AnnotationAttributes targetAttribs =
303-
AnnotationAttributes.fromMap(metaAnnotations.getAnnotationAttributes(targetAnnotationType, classValuesAsString));
304-
if (targetAttribs != null) {
305-
allAttribs.add(targetAttribs);
300+
for (String annotationType : metadata.getAnnotationTypes()) {
301+
getImports(annotationType, imports, visited);
306302
}
307303
}
308-
309-
AnnotationAttributes localAttribs =
310-
AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(targetAnnotationType, classValuesAsString));
311-
if (localAttribs != null) {
312-
allAttribs.add(localAttribs);
313-
}
314-
315-
return allAttribs;
304+
return imports;
316305
}
317306

318307
private void processImport(ConfigurationClass configClass, String[] classesToImport, boolean checkForCircularImports) throws IOException {
@@ -451,5 +440,4 @@ public CircularImportProblem(ConfigurationClass attemptedImport, Stack<Configura
451440
new Location(importStack.peek().getResource(), metadata));
452441
}
453442
}
454-
455443
}

org.springframework.context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@
2525
import org.springframework.beans.BeansException;
2626
import org.springframework.beans.factory.BeanFactory;
2727
import org.springframework.beans.factory.BeanFactoryAware;
28+
import org.springframework.beans.factory.config.BeanDefinition;
2829
import org.springframework.beans.factory.config.BeanPostProcessor;
30+
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
31+
import org.springframework.beans.factory.support.GenericBeanDefinition;
2932
import org.springframework.core.annotation.AnnotationAttributes;
3033
import org.springframework.core.type.AnnotationMetadata;
3134
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
35+
import org.springframework.util.Assert;
3236

3337
import static org.hamcrest.CoreMatchers.*;
3438
import static org.junit.Assert.*;
@@ -77,6 +81,24 @@ public void indirectlyAnnotatedWithImport() {
7781
assertThat(foo, is("xyz"));
7882
}
7983

84+
@Test
85+
public void importRegistrar() throws Exception {
86+
ImportedRegistrar.called = false;
87+
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
88+
ctx.register(ImportingRegistrarConfig.class);
89+
ctx.refresh();
90+
assertNotNull(ctx.getBean("registrarImportedBean"));
91+
}
92+
93+
@Test
94+
public void importRegistrarWithImport() throws Exception {
95+
ImportedRegistrar.called = false;
96+
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
97+
ctx.register(ImportingRegistrarConfigWithImport.class);
98+
ctx.refresh();
99+
assertNotNull(ctx.getBean("registrarImportedBean"));
100+
assertNotNull(ctx.getBean(ImportedConfig.class));
101+
}
80102

81103
@Configuration
82104
@Import(ImportedConfig.class)
@@ -131,4 +153,35 @@ public Object postProcessAfterInitialization(Object bean, String beanName) throw
131153
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
132154
}
133155
}
156+
157+
@Configuration
158+
@EnableImportRegistrar
159+
static class ImportingRegistrarConfig {
160+
}
161+
162+
@Configuration
163+
@EnableImportRegistrar
164+
@Import(ImportedConfig.class)
165+
static class ImportingRegistrarConfigWithImport {
166+
}
167+
168+
@Target(ElementType.TYPE)
169+
@Retention(RetentionPolicy.RUNTIME)
170+
@Import(ImportedRegistrar.class)
171+
public @interface EnableImportRegistrar {
172+
}
173+
174+
static class ImportedRegistrar implements ImportBeanDefinitionRegistrar {
175+
176+
static boolean called;
177+
178+
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
179+
BeanDefinitionRegistry registry) {
180+
BeanDefinition beanDefinition = new GenericBeanDefinition();
181+
beanDefinition.setBeanClassName(String.class.getName());
182+
registry.registerBeanDefinition("registrarImportedBean", beanDefinition );
183+
Assert.state(called == false, "ImportedRegistrar called twice");
184+
called = true;
185+
}
186+
}
134187
}

0 commit comments

Comments
 (0)