• SpringBoot启动类自动包扫描 三种方式


    spring-boot-scan-packages-example

    SpringBoot启动类自动包扫描 三种方式
    fox.风

    com.fox: 为第三方包路径

    方式一 @SpringBootApplication 中 scanBasePackages 引入包

    请看 example 案例

    @SpringBootApplication(scanBasePackages={"com.fox"})
    
    • 1

    方式二 配置 BeanConfigScanConfig 写好注解

    请看 example2 案例

    请看 BeanConfigScanConfig 文件

    @ComponentScans(value =
            {@ComponentScan(value = "com.fox")})
    @EntityScan(basePackages = {"com.fox"})
    @Configuration
    public class BeanConfigScanConfig implements EnvironmentAware {
    
        @Override
        public void setEnvironment(Environment environment) {
            System.out.println("##################################初始化 BeanConfigScan ################################################");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    注解包 扫描有顺序

    com.fox : 为第三包路径

    方式三 在 SpringBoot Application 启动文件中 配置注解 @ComponentScan

    请看 example3 案例

    编辑 Example3Application 文件,注解如下

    @SpringBootApplication
    @ComponentScan(value = {"com.example", "com.fox"})
    
    • 1
    • 2

    注解包 扫描有顺序

    com.example : 为 当前项目包路径

    com.fox : 为第三包路径

    方式四 在第三方包内(有权限修改) 配置 BeanConfigScanConfig 写好注解,最后配置 spring.factories

    请看 example5 案例

    编辑配置文件 BeanConfigScanConfig

    @ComponentScans(value =
            {@ComponentScan(value = "com.fox")})
    @EntityScan(basePackages = {"com.fox"})
    @Configuration
    public class BeanConfigScanConfig implements EnvironmentAware {
    
        @Override
        public void setEnvironment(Environment environment) {
            System.out.println("##################################初始化 BeanConfigScan ################################################");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在resources 文件夹下创建 META-INF 文件夹,在META-INF 文件夹内创建 spring.factories 文件
    spring.factories 文件内容如下

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=
        com.example.configuration.BeanConfigScanConfig
    
    • 1
    • 2

    代码: https://gitee.com/fox-demo/spring-boot-scan-packages-example

  • 相关阅读:
    Go基础11-理解Go语言的包导入
    阿里巴巴为什么能抗住90秒100亿?看完这篇你就明白了!
    使用brainconn工具绘制的大脑连接数据,比BrainNet更方便和灵活
    阿里面试面试题
    c++ 学习之类型,常量以及变量的重点知识
    android UI到系统揭秘
    一个简单的HTML篮球网页【学生网页设计作业源码】
    3D着色器(OpenGL)
    244:vue+openlayers 显示滚动效果的线段Line
    公交实时位置查询APP
  • 原文地址:https://blog.csdn.net/Bejpse/article/details/126511485