【Springboot】排除多余依赖与Bean实例
一、背景: 引入公共包之后,需要排除部分不需要的包和bean,给当前服务最大程度减重
二、实现:
1.在pom.xml排除依赖
2.在启动类上添加扫描排除项
@ComponentScan(basePackages = {"com.xxx"}, excludeFilters = { @ComponentScan.Filter( type = FilterType.CUSTOM, classes = {ScanExcludeFilter.class} ) }) public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
其中,FilterType有以下几种:
public enum FilterType { ANNOTATION, //按照注解过滤 ASSIGNABLE_TYPE, //按照类型过滤 ASPECTJ,//按照ASPECTJ表达式过滤 REGEX,//按照正则表达式过滤 CUSTOM;//按照自定义的过滤规则过滤 private FilterType() { } }
3.实现TypeFilter
public class ScanExcludeFilter implements TypeFilter { // 需要的Bean包含的关键字 private static final List<String> containsKeyWords = Arrays.asList( "core.config", "common.dao" ); // 不能的Bean包含的关键字 private static final List<String> excludeKeyWords = Arrays.asList( "XxxConfig" ); @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { ClassMetadata classMetadata = metadataReader.getClassMetadata(); String className = classMetadata.getClassName(); if (!className.contains("ema")) { return false; } // 先走排除 if (isExculdeBean(className)) { return true; } // 再看是否真的满足 return !needContains(className); } // 匹配不需要的bean private boolean isExculdeBean(String className) { for (String keyword : excludeKeyWords) { if (className.contains(keyword)) { return true; } } return false; } // 匹配需要的bean private boolean needContains(String className) { for (String keyword : containsKeyWords) { if (className.contains(keyword)) { return true; } } return false; } }