spring通过@ComponentScan注解来指定扫描的范围。其中可通过 excludeFilters来指定哪些范围可以被排除在外。当type = FilterType.CUSTOM时,我们可以通过自定义代码的方式来灵活判断哪些类不用来示例化。
具体实现过程如下:
- 在配置类或启动类上加上如下注解
#type = FilterType.CUSTOM 代表自定义类型;classes = CustomFilterType.class自定义的扫描规则判断实现类。
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM,classes = CustomTypeFilter.class)})
- 实现自定义判断规则
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import java.io.IOException;
public class CustomTypeFilter implements TypeFilter {
/**
* 对于excludeFilters功能来说,返回值为true表示需要被排除在外,返回值为false表示不需要排除在外
* 对于includeFilters功能与excludeFilters相反
* @param metadataReader
* @param metadataReaderFactory
* @return
* @throws IOException
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
String className = metadataReader.getClassMetadata().getClassName();
//todo:自定义处理逻辑
if (className.equals("XXX")){
return true;
}
return false;
}
}
如果还有其他使用需求,详细情况可以参考@ComponentScan.Filter的使用说明。