一、注解说明
@ComponentScan:会自动扫描包路径下面的所有@Controller、@Service、@Repository、@Component 的类
它里面的属性: value指定扫描的包,includeFilters包含那些过滤,excludeFilters不包含那些过滤,useDefaultFilters默认的过滤规则是开启的,如果我们要自定义的话是要关闭的。其中@Filters是一个过滤器的接口。
@Filters 指过滤规则,FilterType指定过滤的规则(
FilterType.ANNOTATION:按照注解
FilterType.ASSIGNABLE_TYPE:按照给定的类型;
FilterType.ASPECTJ:使用ASPECTJ表达式
FilterType.REGEX:使用正则指定
FilterType.CUSTOM:使用自定义规则)
classes指定过滤的类
示列如下:
package com.guang.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import com.guang.entity.Person;
@Configuration
// @ComponentScan("包路径") 会自动扫描包路径下面的所有@Controller、@Service、@Repository、@Component 的类
// includeFilters 指定包含扫描的内容
// excludeFilters 指定不包含的内容
// @Filter 指定过滤规则,type指定扫描的规则(注解,正则,自定义,ASPECTJ表达式),classes指定的扫描的规则类
@ComponentScan(basePackages = {"com.guang"},
includeFilters = @Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = {Repository.class}),
includeFilters = @Filter(type = FilterType.CUSTOM, classes = {FilterCustom.class}),
useDefaultFilters = false)
public class Myconfig {
@Bean("person")
public Person person01() {
return new Person("aiha", 25);
}
}
二、如果我们在使用自定义(
includeFilters = @Filter(type = FilterType.CUSTOM, classes = {自己定义的类})
)过滤规则的时候,我们自己定义的类要实现
TypeFilter
接口,例如:
package com.guang.config;
import java.io.IOException;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
/**
* 自定义的过滤规则,在自动扫描的时候用,自定义过滤的时候不在使用默认的规则了
*
* @ClassName FilterCustom
* @author xxx
* @date xxx
* @version xxx
*/
public class FilterCustom implements TypeFilter {
/**
*
* @Title: match
* @Description: 覆盖方法注释标签说明
* @param metadataReader 读取的当前正在扫描类的信息
* @param metadataReaderFactory 类工厂中其它类的信息
* @return
* @throws IOException
* @see org.springframework.core.type.filter.TypeFilter#match(org.springframework.core.type.classreading.MetadataReader,
* org.springframework.core.type.classreading.MetadataReaderFactory)
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
// 获取当前类注解的信息
// AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
// 获取当前正在扫描类的信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
// 获取当前类路径的信息
// Resource resource = metadataReader.getResource();
if (classMetadata.getClassName().startsWith("person")) {
return true;
}
return false;
}
}
版权声明:本文为u010285684原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。