具有依赖性且没有@ComponentScan的Spring引导自动配置

Nit*_*tul 3 dependency-injection spring-boot component-scan spring-boot-actuator spring-boot-starter

Spring引导提供@ComponentScan了查找要扫描的包.

我正在建立一个@RestControllers内部package com.mylib.controller有的库.还有其他类以及不同包中的构造型注释.

所以,如果有人正在使用com.myapp 基础包开发SpringBoot Application .他在他的应用程序中使用我的库.他需要提一下@ComponentScan("com.mylib")发现图书馆的刻板印象.

有没有办法扫描组件而不包括库包@ComponentScan

由于spring-boot-starter-actuator暴露其端点只是依赖,没有定义@ComponentScan.或者无论应用程序基础包如何扫描的任何默认包.

Dar*_*the 5

您可以使用与Spring提供的Starters相同的样式创建Spring Boot Starter.它们本质上是一个jar'd库,带有一个spring.factories指向@Configuration类的文件,在那里加载一些其他注释以提供overriding/bean back off(@ConditionalOnMissingBean)并且通常提供它们自己的@ConfigurationProperties.

StéphaneNic​​oll提供了一个如何构建一个的优秀演示.

https://github.com/snicoll-demos/hello-service-auto-configuration

它也在Spring Boot文档中有记录.https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html

图书馆的方法也可行,但我认为没有让它成为首发的好处.此外,对于任何库/启动器,我建议删除@ComponentScan和只是定义bean中的bean @Configuration.@RestController如果你@Bean在配置中创建一个类型,这将适用于类似的类型将正常工作.