SpringBoot 排除一些包的注入
文章目录
- 需求
- 一、使用 @ComponentScan
需求
在系统迭代的过程中,有一些 Controller 大批量的不再使用,或者有一些接口我们不想再提供给外界
一、使用 @ComponentScan
@SpringBootApplication(scanBasePackages = "com.zrb.excludeSomePkg")
@ComponentScan(
basePackages = "com.zrb.excludeSomePkg",
// 排除的过滤器
excludeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = CustomExcludeFilter.class)
}
)
public class SpringBootAnnoExample {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(SpringBootAnnoExample.class);
Pk1Service bean1 = applicationContext.getBean(Pk1Service.class);
Pk2Service bean2 = applicationContext.getBean(Pk2Service.class);
System.out.println(bean2);
System.out.println(bean1);
}
}
public class CustomExcludeFilter implements TypeFilter {
/**
* 忽略pk1包下的所有类
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
String className = metadataReader.getClassMetadata().getClassName();
return className.startsWith("com.zrb.excludeSomePkg.pk1");
}
}