ClassPathScanningCandidateComponentProvider.java 19.8 KB
Newer Older
A
Arjen Poutsma 已提交
1
/*
W
Polish  
www 已提交
2
 * Copyright 2002-2019 the original author or authors.
A
Arjen Poutsma 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.annotation;

import java.io.IOException;
20
import java.lang.annotation.Annotation;
21
import java.util.HashSet;
A
Arjen Poutsma 已提交
22 23 24 25 26 27 28
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
29

A
Arjen Poutsma 已提交
30 31
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
32
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
33
import org.springframework.beans.factory.annotation.Lookup;
A
Arjen Poutsma 已提交
34
import org.springframework.beans.factory.config.BeanDefinition;
35
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
A
Arjen Poutsma 已提交
36
import org.springframework.context.ResourceLoaderAware;
37 38 39
import org.springframework.context.index.CandidateComponentsIndex;
import org.springframework.context.index.CandidateComponentsIndexLoader;
import org.springframework.core.annotation.AnnotationUtils;
40 41
import org.springframework.core.env.Environment;
import org.springframework.core.env.EnvironmentCapable;
C
Chris Beams 已提交
42
import org.springframework.core.env.StandardEnvironment;
A
Arjen Poutsma 已提交
43 44
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
45
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
A
Arjen Poutsma 已提交
46 47
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
48
import org.springframework.core.type.AnnotationMetadata;
A
Arjen Poutsma 已提交
49 50 51 52
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.AnnotationTypeFilter;
53
import org.springframework.core.type.filter.AssignableTypeFilter;
A
Arjen Poutsma 已提交
54
import org.springframework.core.type.filter.TypeFilter;
55
import org.springframework.lang.Nullable;
A
Arjen Poutsma 已提交
56 57
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
58
import org.springframework.stereotype.Indexed;
A
Arjen Poutsma 已提交
59 60 61 62 63 64
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
65 66 67 68
 * A component provider that provides candidate components from a base package. Can
 * use {@link CandidateComponentsIndex the index} if it is available of scans the
 * classpath otherwise. Candidate components are identified by applying exclude and
 * include filters. {@link AnnotationTypeFilter}, {@link AssignableTypeFilter} include
69
 * filters on an annotation/superclass that are annotated with {@link Indexed} are
70 71
 * supported: if any other include filter is specified, the index is ignored and
 * classpath scanning is used instead.
A
Arjen Poutsma 已提交
72 73 74
 *
 * <p>This implementation is based on Spring's
 * {@link org.springframework.core.type.classreading.MetadataReader MetadataReader}
75
 * facility, backed by an ASM {@link org.springframework.asm.ClassReader ClassReader}.
A
Arjen Poutsma 已提交
76 77 78 79
 *
 * @author Mark Fisher
 * @author Juergen Hoeller
 * @author Ramnivas Laddad
80
 * @author Chris Beams
81
 * @author Stephane Nicoll
A
Arjen Poutsma 已提交
82 83 84 85
 * @since 2.5
 * @see org.springframework.core.type.classreading.MetadataReaderFactory
 * @see org.springframework.core.type.AnnotationMetadata
 * @see ScannedGenericBeanDefinition
86
 * @see CandidateComponentsIndex
A
Arjen Poutsma 已提交
87
 */
88
public class ClassPathScanningCandidateComponentProvider implements EnvironmentCapable, ResourceLoaderAware {
A
Arjen Poutsma 已提交
89

90
	static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
A
Arjen Poutsma 已提交
91 92


93
	protected final Log logger = LogFactory.getLog(getClass());
94

A
Arjen Poutsma 已提交
95 96
	private String resourcePattern = DEFAULT_RESOURCE_PATTERN;

97
	private final List<TypeFilter> includeFilters = new LinkedList<>();
A
Arjen Poutsma 已提交
98

99
	private final List<TypeFilter> excludeFilters = new LinkedList<>();
A
Arjen Poutsma 已提交
100

101
	@Nullable
102 103
	private Environment environment;

104
	@Nullable
105 106
	private ConditionEvaluator conditionEvaluator;

107
	@Nullable
108 109
	private ResourcePatternResolver resourcePatternResolver;

110
	@Nullable
111 112
	private MetadataReaderFactory metadataReaderFactory;

113
	@Nullable
114 115 116 117 118 119 120 121 122
	private CandidateComponentsIndex componentsIndex;


	/**
	 * Protected constructor for flexible subclass initialization.
	 * @since 4.3.6
	 */
	protected ClassPathScanningCandidateComponentProvider() {
	}
A
Arjen Poutsma 已提交
123 124

	/**
125
	 * Create a ClassPathScanningCandidateComponentProvider with a {@link StandardEnvironment}.
A
Arjen Poutsma 已提交
126 127 128 129 130 131 132
	 * @param useDefaultFilters whether to register the default filters for the
	 * {@link Component @Component}, {@link Repository @Repository},
	 * {@link Service @Service}, and {@link Controller @Controller}
	 * stereotype annotations
	 * @see #registerDefaultFilters()
	 */
	public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) {
133 134 135
		this(useDefaultFilters, new StandardEnvironment());
	}

136 137 138 139 140 141 142 143 144
	/**
	 * Create a ClassPathScanningCandidateComponentProvider with the given {@link Environment}.
	 * @param useDefaultFilters whether to register the default filters for the
	 * {@link Component @Component}, {@link Repository @Repository},
	 * {@link Service @Service}, and {@link Controller @Controller}
	 * stereotype annotations
	 * @param environment the Environment to use
	 * @see #registerDefaultFilters()
	 */
145
	public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters, Environment environment) {
A
Arjen Poutsma 已提交
146 147 148
		if (useDefaultFilters) {
			registerDefaultFilters();
		}
149 150
		setEnvironment(environment);
		setResourceLoader(null);
151 152
	}

153

A
Arjen Poutsma 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
	/**
	 * Set the resource pattern to use when scanning the classpath.
	 * This value will be appended to each base package name.
	 * @see #findCandidateComponents(String)
	 * @see #DEFAULT_RESOURCE_PATTERN
	 */
	public void setResourcePattern(String resourcePattern) {
		Assert.notNull(resourcePattern, "'resourcePattern' must not be null");
		this.resourcePattern = resourcePattern;
	}

	/**
	 * Add an include type filter to the <i>end</i> of the inclusion list.
	 */
	public void addIncludeFilter(TypeFilter includeFilter) {
		this.includeFilters.add(includeFilter);
	}

	/**
	 * Add an exclude type filter to the <i>front</i> of the exclusion list.
	 */
	public void addExcludeFilter(TypeFilter excludeFilter) {
		this.excludeFilters.add(0, excludeFilter);
	}

	/**
	 * Reset the configured type filters.
	 * @param useDefaultFilters whether to re-register the default filters for
	 * the {@link Component @Component}, {@link Repository @Repository},
	 * {@link Service @Service}, and {@link Controller @Controller}
	 * stereotype annotations
	 * @see #registerDefaultFilters()
	 */
	public void resetFilters(boolean useDefaultFilters) {
		this.includeFilters.clear();
		this.excludeFilters.clear();
		if (useDefaultFilters) {
			registerDefaultFilters();
		}
	}

	/**
	 * Register the default filter for {@link Component @Component}.
J
Juergen Hoeller 已提交
197
	 * <p>This will implicitly register all annotations that have the
A
Arjen Poutsma 已提交
198 199 200
	 * {@link Component @Component} meta-annotation including the
	 * {@link Repository @Repository}, {@link Service @Service}, and
	 * {@link Controller @Controller} stereotype annotations.
J
Juergen Hoeller 已提交
201 202 203
	 * <p>Also supports Java EE 6's {@link javax.annotation.ManagedBean} and
	 * JSR-330's {@link javax.inject.Named} annotations, if available.
	 *
A
Arjen Poutsma 已提交
204
	 */
205
	@SuppressWarnings("unchecked")
A
Arjen Poutsma 已提交
206 207
	protected void registerDefaultFilters() {
		this.includeFilters.add(new AnnotationTypeFilter(Component.class));
208
		ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
209 210
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
211
					((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
212
			logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
213 214 215 216
		}
		catch (ClassNotFoundException ex) {
			// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
		}
217 218
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
219
					((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
220
			logger.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
221 222 223 224
		}
		catch (ClassNotFoundException ex) {
			// JSR-330 API not available - simply skip.
		}
A
Arjen Poutsma 已提交
225 226
	}

227 228 229 230 231 232 233 234 235 236 237 238 239 240
	/**
	 * Set the Environment to use when resolving placeholders and evaluating
	 * {@link Conditional @Conditional}-annotated component classes.
	 * <p>The default is a {@link StandardEnvironment}.
	 * @param environment the Environment to use
	 */
	public void setEnvironment(Environment environment) {
		Assert.notNull(environment, "Environment must not be null");
		this.environment = environment;
		this.conditionEvaluator = null;
	}

	@Override
	public final Environment getEnvironment() {
241 242 243
		if (this.environment == null) {
			this.environment = new StandardEnvironment();
		}
244 245 246 247 248 249
		return this.environment;
	}

	/**
	 * Return the {@link BeanDefinitionRegistry} used by this scanner, if any.
	 */
250
	@Nullable
251 252 253 254 255 256 257 258 259 260 261 262 263
	protected BeanDefinitionRegistry getRegistry() {
		return null;
	}

	/**
	 * Set the {@link ResourceLoader} to use for resource locations.
	 * This will typically be a {@link ResourcePatternResolver} implementation.
	 * <p>Default is a {@code PathMatchingResourcePatternResolver}, also capable of
	 * resource pattern resolving through the {@code ResourcePatternResolver} interface.
	 * @see org.springframework.core.io.support.ResourcePatternResolver
	 * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
	 */
	@Override
264
	public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
265 266 267 268 269 270 271 272 273
		this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
		this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
		this.componentsIndex = CandidateComponentsIndexLoader.loadIndex(this.resourcePatternResolver.getClassLoader());
	}

	/**
	 * Return the ResourceLoader that this component provider uses.
	 */
	public final ResourceLoader getResourceLoader() {
274 275 276 277 278 279 280
		return getResourcePatternResolver();
	}

	private ResourcePatternResolver getResourcePatternResolver() {
		if (this.resourcePatternResolver == null) {
			this.resourcePatternResolver = new PathMatchingResourcePatternResolver();
		}
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
		return this.resourcePatternResolver;
	}

	/**
	 * Set the {@link MetadataReaderFactory} to use.
	 * <p>Default is a {@link CachingMetadataReaderFactory} for the specified
	 * {@linkplain #setResourceLoader resource loader}.
	 * <p>Call this setter method <i>after</i> {@link #setResourceLoader} in order
	 * for the given MetadataReaderFactory to override the default factory.
	 */
	public void setMetadataReaderFactory(MetadataReaderFactory metadataReaderFactory) {
		this.metadataReaderFactory = metadataReaderFactory;
	}

	/**
	 * Return the MetadataReaderFactory used by this component provider.
	 */
	public final MetadataReaderFactory getMetadataReaderFactory() {
299 300 301
		if (this.metadataReaderFactory == null) {
			this.metadataReaderFactory = new CachingMetadataReaderFactory();
		}
302 303 304
		return this.metadataReaderFactory;
	}

A
Arjen Poutsma 已提交
305 306 307 308 309 310 311

	/**
	 * Scan the class path for candidate components.
	 * @param basePackage the package to check for annotated classes
	 * @return a corresponding Set of autodetected bean definitions
	 */
	public Set<BeanDefinition> findCandidateComponents(String basePackage) {
312 313
		if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
			return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
314 315 316 317 318 319
		}
		else {
			return scanCandidateComponents(basePackage);
		}
	}

320 321 322 323 324 325
	/**
	 * Determine if the index can be used by this instance.
	 * @return {@code true} if the index is available and the configuration of this
	 * instance is supported by it, {@code false} otherwise
	 * @since 5.0
	 */
326
	private boolean indexSupportsIncludeFilters() {
327
		for (TypeFilter includeFilter : this.includeFilters) {
328
			if (!indexSupportsIncludeFilter(includeFilter)) {
329 330 331 332 333 334 335 336 337 338 339 340 341
				return false;
			}
		}
		return true;
	}

	/**
	 * Determine if the specified include {@link TypeFilter} is supported by the index.
	 * @param filter the filter to check
	 * @return whether the index supports this include filter
	 * @since 5.0
	 * @see #extractStereotype(TypeFilter)
	 */
342
	private boolean indexSupportsIncludeFilter(TypeFilter filter) {
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
		if (filter instanceof AnnotationTypeFilter) {
			Class<? extends Annotation> annotation = ((AnnotationTypeFilter) filter).getAnnotationType();
			return (AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, annotation) ||
					annotation.getName().startsWith("javax."));
		}
		if (filter instanceof AssignableTypeFilter) {
			Class<?> target = ((AssignableTypeFilter) filter).getTargetType();
			return AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, target);
		}
		return false;
	}

	/**
	 * Extract the stereotype to use for the specified compatible filter.
	 * @param filter the filter to handle
	 * @return the stereotype in the index matching this filter
	 * @since 5.0
360
	 * @see #indexSupportsIncludeFilter(TypeFilter)
361
	 */
362
	@Nullable
363
	private String extractStereotype(TypeFilter filter) {
364 365 366 367 368 369 370 371 372
		if (filter instanceof AnnotationTypeFilter) {
			return ((AnnotationTypeFilter) filter).getAnnotationType().getName();
		}
		if (filter instanceof AssignableTypeFilter) {
			return ((AssignableTypeFilter) filter).getTargetType().getName();
		}
		return null;
	}

373
	private Set<BeanDefinition> addCandidateComponentsFromIndex(CandidateComponentsIndex index, String basePackage) {
374 375 376 377 378 379
		Set<BeanDefinition> candidates = new LinkedHashSet<>();
		try {
			Set<String> types = new HashSet<>();
			for (TypeFilter filter : this.includeFilters) {
				String stereotype = extractStereotype(filter);
				if (stereotype == null) {
W
Polish  
www 已提交
380
					throw new IllegalArgumentException("Failed to extract stereotype from " + filter);
381
				}
382
				types.addAll(index.getCandidateTypes(basePackage, stereotype));
383 384 385 386
			}
			boolean traceEnabled = logger.isTraceEnabled();
			boolean debugEnabled = logger.isDebugEnabled();
			for (String type : types) {
387
				MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(type);
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
				if (isCandidateComponent(metadataReader)) {
					AnnotatedGenericBeanDefinition sbd = new AnnotatedGenericBeanDefinition(
							metadataReader.getAnnotationMetadata());
					if (isCandidateComponent(sbd)) {
						if (debugEnabled) {
							logger.debug("Using candidate component class from index: " + type);
						}
						candidates.add(sbd);
					}
					else {
						if (debugEnabled) {
							logger.debug("Ignored because not a concrete top-level class: " + type);
						}
					}
				}
				else {
					if (traceEnabled) {
						logger.trace("Ignored because matching an exclude filter: " + type);
					}
				}
			}
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
		}
		return candidates;
	}

416
	private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
417
		Set<BeanDefinition> candidates = new LinkedHashSet<>();
A
Arjen Poutsma 已提交
418 419
		try {
			String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
J
Juergen Hoeller 已提交
420
					resolveBasePackage(basePackage) + '/' + this.resourcePattern;
421
			Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
A
Arjen Poutsma 已提交
422 423
			boolean traceEnabled = logger.isTraceEnabled();
			boolean debugEnabled = logger.isDebugEnabled();
424
			for (Resource resource : resources) {
A
Arjen Poutsma 已提交
425 426 427 428
				if (traceEnabled) {
					logger.trace("Scanning " + resource);
				}
				if (resource.isReadable()) {
429
					try {
430
						MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
431 432 433 434 435 436 437 438 439 440 441 442 443 444
						if (isCandidateComponent(metadataReader)) {
							ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
							sbd.setResource(resource);
							sbd.setSource(resource);
							if (isCandidateComponent(sbd)) {
								if (debugEnabled) {
									logger.debug("Identified candidate component class: " + resource);
								}
								candidates.add(sbd);
							}
							else {
								if (debugEnabled) {
									logger.debug("Ignored because not a concrete top-level class: " + resource);
								}
A
Arjen Poutsma 已提交
445 446 447
							}
						}
						else {
448 449
							if (traceEnabled) {
								logger.trace("Ignored because not matching any filter: " + resource);
A
Arjen Poutsma 已提交
450 451 452
							}
						}
					}
453 454 455
					catch (Throwable ex) {
						throw new BeanDefinitionStoreException(
								"Failed to read candidate component class: " + resource, ex);
A
Arjen Poutsma 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469
					}
				}
				else {
					if (traceEnabled) {
						logger.trace("Ignored because not readable: " + resource);
					}
				}
			}
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
		}
		return candidates;
	}
470

A
Arjen Poutsma 已提交
471 472 473 474 475 476 477 478 479 480

	/**
	 * Resolve the specified base package into a pattern specification for
	 * the package search path.
	 * <p>The default implementation resolves placeholders against system properties,
	 * and converts a "."-based package path to a "/"-based resource path.
	 * @param basePackage the base package as specified by the user
	 * @return the pattern specification to be used for package searching
	 */
	protected String resolveBasePackage(String basePackage) {
481
		return ClassUtils.convertClassNameToResourcePath(getEnvironment().resolveRequiredPlaceholders(basePackage));
A
Arjen Poutsma 已提交
482 483 484 485 486 487 488 489 490 491
	}

	/**
	 * Determine whether the given class does not match any exclude filter
	 * and does match at least one include filter.
	 * @param metadataReader the ASM ClassReader for the class
	 * @return whether the class qualifies as a candidate component
	 */
	protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
		for (TypeFilter tf : this.excludeFilters) {
492
			if (tf.match(metadataReader, getMetadataReaderFactory())) {
A
Arjen Poutsma 已提交
493 494 495 496
				return false;
			}
		}
		for (TypeFilter tf : this.includeFilters) {
497
			if (tf.match(metadataReader, getMetadataReaderFactory())) {
498
				return isConditionMatch(metadataReader);
499 500
			}
		}
501
		return false;
502 503
	}

504 505 506 507 508 509 510
	/**
	 * Determine whether the given class is a candidate component based on any
	 * {@code @Conditional} annotations.
	 * @param metadataReader the ASM ClassReader for the class
	 * @return whether the class qualifies as a candidate component
	 */
	private boolean isConditionMatch(MetadataReader metadataReader) {
511
		if (this.conditionEvaluator == null) {
512 513
			this.conditionEvaluator =
					new ConditionEvaluator(getRegistry(), this.environment, this.resourcePatternResolver);
514
		}
J
Juergen Hoeller 已提交
515
		return !this.conditionEvaluator.shouldSkip(metadataReader.getAnnotationMetadata());
516 517
	}

A
Arjen Poutsma 已提交
518 519
	/**
	 * Determine whether the given bean definition qualifies as candidate.
520 521 522
	 * <p>The default implementation checks whether the class is not an interface
	 * and not dependent on an enclosing class.
	 * <p>Can be overridden in subclasses.
A
Arjen Poutsma 已提交
523 524 525 526
	 * @param beanDefinition the bean definition to check
	 * @return whether the bean definition qualifies as a candidate component
	 */
	protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
527 528 529
		AnnotationMetadata metadata = beanDefinition.getMetadata();
		return (metadata.isIndependent() && (metadata.isConcrete() ||
				(metadata.isAbstract() && metadata.hasAnnotatedMethods(Lookup.class.getName()))));
A
Arjen Poutsma 已提交
530 531
	}

532 533

	/**
534
	 * Clear the local metadata cache, if any, removing all cached class metadata.
535 536 537
	 */
	public void clearCache() {
		if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
538 539
			// Clear cache in externally provided MetadataReaderFactory; this is a no-op
			// for a shared cache since it'll be cleared by the ApplicationContext.
540 541 542 543
			((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
		}
	}

A
Arjen Poutsma 已提交
544
}