ClassPathScanningCandidateComponentProvider.java 13.2 KB
Newer Older
A
Arjen Poutsma 已提交
1
/*
2
 * Copyright 2002-2012 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;
A
Arjen Poutsma 已提交
21 22 23 24 25 26 27
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;
28

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

/**
 * A component provider that scans the classpath from a base package. It then
 * applies exclude and include filters to the resulting classes to find candidates.
 *
 * <p>This implementation is based on Spring's
 * {@link org.springframework.core.type.classreading.MetadataReader MetadataReader}
61
 * facility, backed by an ASM {@link org.springframework.asm.ClassReader ClassReader}.
A
Arjen Poutsma 已提交
62 63 64 65
 *
 * @author Mark Fisher
 * @author Juergen Hoeller
 * @author Ramnivas Laddad
66
 * @author Chris Beams
A
Arjen Poutsma 已提交
67 68 69 70 71
 * @since 2.5
 * @see org.springframework.core.type.classreading.MetadataReaderFactory
 * @see org.springframework.core.type.AnnotationMetadata
 * @see ScannedGenericBeanDefinition
 */
72
public class ClassPathScanningCandidateComponentProvider implements EnvironmentCapable, ResourceLoaderAware {
A
Arjen Poutsma 已提交
73

74
	static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
A
Arjen Poutsma 已提交
75 76 77

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

78
	private Environment environment;
79

A
Arjen Poutsma 已提交
80 81
	private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

82 83
	private MetadataReaderFactory metadataReaderFactory =
			new CachingMetadataReaderFactory(this.resourcePatternResolver);
A
Arjen Poutsma 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

	private String resourcePattern = DEFAULT_RESOURCE_PATTERN;

	private final List<TypeFilter> includeFilters = new LinkedList<TypeFilter>();

	private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>();


	/**
	 * Create a ClassPathScanningCandidateComponentProvider.
	 * @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) {
101 102 103 104
		this(useDefaultFilters, new StandardEnvironment());
	}

	public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters, Environment environment) {
A
Arjen Poutsma 已提交
105 106 107
		if (useDefaultFilters) {
			registerDefaultFilters();
		}
108
		this.environment = environment;
A
Arjen Poutsma 已提交
109 110 111 112 113 114 115 116 117 118 119
	}


	/**
	 * Set the ResourceLoader to use for resource locations.
	 * This will typically be a ResourcePatternResolver implementation.
	 * <p>Default is PathMatchingResourcePatternResolver, also capable of
	 * resource pattern resolving through the ResourcePatternResolver interface.
	 * @see org.springframework.core.io.support.ResourcePatternResolver
	 * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
	 */
120
	@Override
A
Arjen Poutsma 已提交
121 122 123 124 125
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
		this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
	}

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	/**
	 * Return the ResourceLoader that this component provider uses.
	 */
	public final ResourceLoader getResourceLoader() {
		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() {
		return this.metadataReaderFactory;
	}

151
	/**
152 153
	 * Set the Environment to use when resolving placeholders and evaluating
	 * {@link Profile @Profile}-annotated component classes.
154
	 * <p>The default is a {@link StandardEnvironment}
155
	 * @param environment the Environment to use
156 157 158 159 160
	 */
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}

161
	@Override
162
	public final Environment getEnvironment() {
163 164 165
		return this.environment;
	}

A
Arjen Poutsma 已提交
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 197 198 199 200 201 202 203 204 205 206 207 208
	/**
	 * 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 已提交
209
	 * <p>This will implicitly register all annotations that have the
A
Arjen Poutsma 已提交
210 211 212
	 * {@link Component @Component} meta-annotation including the
	 * {@link Repository @Repository}, {@link Service @Service}, and
	 * {@link Controller @Controller} stereotype annotations.
J
Juergen Hoeller 已提交
213 214 215
	 * <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 已提交
216
	 */
217
	@SuppressWarnings("unchecked")
A
Arjen Poutsma 已提交
218 219
	protected void registerDefaultFilters() {
		this.includeFilters.add(new AnnotationTypeFilter(Component.class));
220
		ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
221 222
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
223
					((Class<? extends Annotation>) cl.loadClass("javax.annotation.ManagedBean")), false));
224 225 226 227 228
			logger.info("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
		}
		catch (ClassNotFoundException ex) {
			// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
		}
229 230
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
231
					((Class<? extends Annotation>) cl.loadClass("javax.inject.Named")), false));
232
			logger.info("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
233 234 235 236
		}
		catch (ClassNotFoundException ex) {
			// JSR-330 API not available - simply skip.
		}
A
Arjen Poutsma 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
	}


	/**
	 * 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) {
		Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
		try {
			String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
					resolveBasePackage(basePackage) + "/" + this.resourcePattern;
			Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
			boolean traceEnabled = logger.isTraceEnabled();
			boolean debugEnabled = logger.isDebugEnabled();
253
			for (Resource resource : resources) {
A
Arjen Poutsma 已提交
254 255 256 257
				if (traceEnabled) {
					logger.trace("Scanning " + resource);
				}
				if (resource.isReadable()) {
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
					try {
						MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
						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 已提交
274 275 276
							}
						}
						else {
277 278
							if (traceEnabled) {
								logger.trace("Ignored because not matching any filter: " + resource);
A
Arjen Poutsma 已提交
279 280 281
							}
						}
					}
282 283 284
					catch (Throwable ex) {
						throw new BeanDefinitionStoreException(
								"Failed to read candidate component class: " + resource, ex);
A
Arjen Poutsma 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298
					}
				}
				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;
	}
299

A
Arjen Poutsma 已提交
300 301 302 303 304 305 306 307 308 309

	/**
	 * 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) {
310
		return ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(basePackage));
A
Arjen Poutsma 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
	}

	/**
	 * 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) {
			if (tf.match(metadataReader, this.metadataReaderFactory)) {
				return false;
			}
		}
		for (TypeFilter tf : this.includeFilters) {
			if (tf.match(metadataReader, this.metadataReaderFactory)) {
327
				AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
328
				if (!metadata.isAnnotated(Profile.class.getName())) {
329
					return true;
330
				}
331 332
				AnnotationAttributes profile = MetadataUtils.attributesFor(metadata, Profile.class);
				return this.environment.acceptsProfiles(profile.getStringArray("value"));
333 334
			}
		}
335
		return false;
336 337
	}

A
Arjen Poutsma 已提交
338 339 340 341 342 343 344 345 346 347 348
	/**
	 * Determine whether the given bean definition qualifies as candidate.
	 * <p>The default implementation checks whether the class is concrete
	 * (i.e. not abstract and not an interface). Can be overridden in subclasses.
	 * @param beanDefinition the bean definition to check
	 * @return whether the bean definition qualifies as a candidate component
	 */
	protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
		return (beanDefinition.getMetadata().isConcrete() && beanDefinition.getMetadata().isIndependent());
	}

349 350 351 352 353 354 355 356 357 358

	/**
	 * Clear the underlying metadata cache, removing all cached class metadata.
	 */
	public void clearCache() {
		if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
			((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
		}
	}

A
Arjen Poutsma 已提交
359
}