Skip to content

Commit d547570

Browse files
committed
Merge branch 'backport-SPR-9925' into 3.1.x
* backport-SPR-9925: Backport "Polish @imports search code" Backport "Ensure @imports are processed in correct order" Backport "Prevent duplicate @import processing" Backport "Polish Javadoc for @import"
2 parents a420e84 + a9290d8 commit d547570

File tree

3 files changed

+89
-47
lines changed

3 files changed

+89
-47
lines changed

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

Lines changed: 33 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,16 @@
1616

1717
package org.springframework.context.annotation;
1818

19+
import static org.springframework.context.annotation.MetadataUtils.attributesFor;
20+
1921
import java.io.IOException;
20-
import java.lang.annotation.Annotation;
21-
import java.util.ArrayList;
22+
import java.util.Arrays;
2223
import java.util.Collections;
2324
import java.util.Comparator;
2425
import java.util.HashMap;
26+
import java.util.HashSet;
2527
import java.util.Iterator;
2628
import java.util.LinkedHashSet;
27-
import java.util.List;
2829
import java.util.Map;
2930
import java.util.Set;
3031
import java.util.Stack;
@@ -51,8 +52,6 @@
5152
import org.springframework.core.type.filter.AssignableTypeFilter;
5253
import org.springframework.util.StringUtils;
5354

54-
import static org.springframework.context.annotation.MetadataUtils.*;
55-
5655
/**
5756
* Parses a {@link Configuration} class definition, populating a collection of
5857
* {@link ConfigurationClass} objects (parsing a single Configuration class may result in
@@ -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+
for (String annotationType : metadata.getAnnotationTypes()) {
293+
imports = getImports(annotationType, imports, visited);
299294
}
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);
295+
Map<String, Object> attributes = metadata.getAnnotationAttributes(Import.class.getName(), true);
296+
if (attributes != null) {
297+
String[] value = (String[]) attributes.get("value");
298+
if (value != null && value.length > 0) {
299+
imports = (imports == null ? new LinkedHashSet<String>() : imports);
300+
imports.addAll(Arrays.asList(value));
301+
}
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/main/java/org/springframework/context/annotation/Import.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2011 the original author or authors.
2+
* Copyright 2002-2012 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.
@@ -53,7 +53,8 @@
5353
public @interface Import {
5454

5555
/**
56-
* The @{@link Configuration} and/or {@link ImportSelector} classes to import.
56+
* The @{@link Configuration}, {@link ImportSelector} and/or
57+
* {@link ImportBeanDefinitionRegistrar} classes to import.
5758
*/
5859
Class<?>[] value();
5960
}

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)