栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

从零搭建开发脚手架 Spring Boot配置扫描多个包目录的多种姿势

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从零搭建开发脚手架 Spring Boot配置扫描多个包目录的多种姿势

文章目录
    • 背景
    • 方案
    • 详解
    • 场景
      • 自定义注解扫描
      • 自定义扫描过滤规则

背景

默认是扫描当前application启动类所在的包及其子包

例如我们的LakerApplication代码如下:

package io.gitee.lakernote;
@SpringBootApplication
public class LakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LakerApplication.class, args);
    }
}

扫描的包为io.gitee.lakernote包及其子包

其@SpringBootApplication内部原理,其实用的就是@ComponentScan注解。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

excludeFilters ?FilterType?你有疑问?下面会详细介绍的,这里你先别管。

如果我们想扫描其他的多个包目录应该怎么做呢?例如,扫描下面2个包。

  • io.gitee.lakernote
  • io.gitee.lakernote2
方案

方式一 @ComponentScan

@SpringBootApplication
@ComponentScan(basePackages = {"io.gitee.lakernote2","io.gitee.lakernote"})
public class LakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LakerApplication.class, args);
    }
}
或者
@SpringBootApplication
@ComponentScan("io.gitee")
public class LakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LakerApplication.class, args);
    }
}
或者
@SpringBootApplication
@ComponentScan("io.gitee.lakernote")
@ComponentScan("io.gitee.lakernote2")
public class LakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LakerApplication.class, args);
    }
}
或者
@SpringBootApplication
@ComponentScan(basePackageClasses = HelloWorldController2.class,basePackages = "io.gitee.lakernote")
public class LakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LakerApplication.class, args);
    }
}

注意@ComponentScan会使默认application的包失效。

方式二 @SpringBootApplication(scanBasePackages = {"xxx"})

原理跟方式一相同

@SpringBootApplication(scanBasePackages = {"io.gitee.lakernote","io.gitee.lakernote2"})
public class LakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LakerApplication.class, args);
    }
}

方式三 @ComponentScans

原理跟方式一相同

@SpringBootApplication
@ComponentScans({
        @ComponentScan(basePackageClasses = HelloWorldController2.class),
        @ComponentScan("io.gitee.lakernote")}
)
public class LakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LakerApplication.class, args);
    }
}
详解

由上可知都是基于@ComponentScan注解做的,那么我们来看下它是如何使用的。

@ComponentScan注解默认就会装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中。

@ComponentScan注解代码如下:
注意看里面的注释,非常详细。

package org.springframework.context.annotation;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(ComponentScans.class)// 这个注解可以同时使用多个
public @interface ComponentScan {
   //  用于指定包的路径,进行扫描io.gitee.lakernote
   @AliasFor("basePackages")
   String[] value() default {};
   //  同value用于指定包的路径,进行扫描 io.gitee.lakernote
   @AliasFor("value")
   String[] basePackages() default {};
   // 用于指定某个类的包的路径进行扫描 HelloService.class
   Class[] basePackageClasses() default {};
   //  bean的名称的生成器
   Class nameGenerator() default BeanNameGenerator.class;
   // 用于解析@Scope注解
   Class scopeResolver() default AnnotationScopeMetadataResolver.class;
   // 用来设置类的代理模式
   ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;
   // 扫描路径 如 resourcePattern = "**
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
            throws IOException {
        //获取当前类注解的信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        //可以通过这个读想获取类的一些元数据信息,如类的class对象、是否是接口、是否有注解、是否是抽象类、父类名称、接口名称、内部包含的之类列表等等
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        //获取当前类资源(类的路径)
        Resource resource = metadataReader.getResource();
        String className = classMetadata.getClassName();
        Class curClass = null;
        try {
            //当前被扫描的类
            curClass = Class.forName(metadataReader.getClassMetadata().getClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //判断curClass是否是IService类型
        boolean result = IService.class.isAssignableFrom(curClass);
        return result;
    }
}

第二步,在@ComponentScan注解中进行配置,如下:

@Configuration
@ComponentScan(value = "io.gitee",
        useDefaultFilters = true, // 装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中
        includeFilters = {
            @ComponentScan.Filter(type = FilterType.CUSTOM,classes = {LakerTypeFilter.class})
        }
)
public class LakerConfig {
}

这个需求也可以这样做,使用FilterType.ASSIGNABLE_TYPE。

@Configuration
@ComponentScan(value = "io.gitee",
        useDefaultFilters = true, // 装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中
        includeFilters = {
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = IService.class)
        }
)
public class LakerConfig {
}

参考:

  • https://blog.csdn.net/huangjhai/article/details/104600328
  • https://blog.csdn.net/chenzoff/article/details/124267671
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/959102.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号