有时候我们会遇到这种情况,需要根据动态获取某个包下的一些特定类。
比如获取”com.xxx.domain”下所有类。
Spring中ClassPathScanningCandidateComponentProvider可以快速完成这项任务。
Spring最核心的一个部分就是Ioc,通过@Component来注解需要委托管理的类。
ClassPathScanningCandidateComponentProvider提供了一个默认的过滤器来处理Component。
protectedvoidregisterDefaultFilters() {
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
try {
this.includeFilters.add(new AnnotationTypeFilter(((Class < ?extends Annotation > ) ClassUtils.forName("javax.annotation.ManagedBean", cl)),false));
logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
}catch(ClassNotFoundException ex) {
//