SpringBoot注解之@ServletComponentScan

先看官方文档

/**
 * Enables scanning for Servlet components ({@link WebFilter filters}, {@link WebServlet
 * servlets}, and {@link WebListener listeners}). Scanning is only performed when using an
 * embedded Servlet container.
 * <p>
 * Typically, one of {@code value}, {@code basePackages}, or {@code basePackageClasses}
 * should be specified to control the packages to be scanned for components. In their
 * absence, scanning will be performed from the package of the class with the annotation.
 */

作用是:扫描@WebFilter,@WebServlet,@WebListener组件.

前提条件是:只支持自带的嵌入式Servlet容器.

用法:通常需要指定三个参数之一:value,basePackages,basePackageClasses.

特例,当不指定三个参数任何一个时,扫描@ServletComponentScan所在包的子包.

 

源码解析:

导入类ServletComponentScanRegistrar

@Import(ServletComponentScanRegistrar.class)

如果已经存在名字为servletComponentRegisteringPostProcessor的bean就重新设置它的ConstructorArgumentValues值.

如果不存在就注册该bean到BeanDefinitionRegistry.然后就跟其它bean一样初始化.

 

private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
		AnnotationAttributes attributes = AnnotationAttributes.fromMap(
				metadata.getAnnotationAttributes(ServletComponentScan.class.getName()));
		String[] basePackages = attributes.getStringArray("basePackages");
		Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
		Set<String> packagesToScan = new LinkedHashSet<String>();
		packagesToScan.addAll(Arrays.asList(basePackages));
		for (Class<?> basePackageClass : basePackageClasses) {
			packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
		}
		if (packagesToScan.isEmpty()) {
			return Collections
					.singleton(ClassUtils.getPackageName(metadata.getClassName()));
		}
		return packagesToScan;
	}

 

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页