spring启动时排除注入指定bean

起因:

项目中引用了其他项目的公共包依赖,公共包中有第三方的配置信息(不合理,不规范),导致必须在配置文件中加入这样配置(写了一堆无用的配置信息还容易报错),启动时注入这些bean时找不到配置信息,导致启动失败

临时解决方案:

排除这些无用且需要读取配置文件的bean
资料参考地址1: https://www.jb51.net/article/218661.htm

使用

排除指定类

@ComponentScan(basePackages = {"com.xx.xx.*"}, excludeFilters =@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {xxx.class}))

排除某些包

@ComponentScan(excludeFilters = 
 {
   @ComponentScan.Filter(type = FilterType.REGEX,pattern = "org.x.xx.other.*") 
 })

示例代码

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

@SpringBootApplication
@MapperScan("org.cuour.sqlserver.dao.mapper")
@ComponentScan(value = "org.x.xx.**",
      excludeFilters = {@ComponentScan.Filter(type = FilterType.REGEX,
            pattern = {"org.x.xx.util.SerialNoUtils","org.x.xx.util.WorkWXUtil"})})
public class AppStartApplication {

   public static void main(String[] args) {
      SpringApplication.run(AppStartApplication.class, args);
   }

}

建议方案

将第三方配置文件单独搞一个模块,易维护

posted @ 2022-12-13 18:12  进击的小蔡鸟  阅读(1788)  评论(0编辑  收藏  举报