Spring 有依赖但没有@ComponentScan 的启动自动配置

Spring boot auto configuration with dependency and without @ComponentScan

Spring boot提供@ComponentScan查找要扫描的包

我正在构建一个图书馆,里面有 @RestControllerspackage com.mylib.controller。还有其他 类 以及不同包中的构造型注释。

因此,如果有人正在使用 com.myapp 基础包开发 Spring 启动应用程序。 他在他的应用程序中使用了我的图书馆。他需要提及 @ComponentScan("com.mylib") 才能发现库的刻板印象组件。

@ComponentScan中有没有不包含库包的扫描组件的方法?

As spring-boot-starter-actuator 仅通过依赖公开其端点,而无需定义 @ComponentScan。或者无论应用程序基础包如何都被扫描的任何默认包。

Spring boot starter 是由Spring设计并由Spring使用的特殊神器。
您可以检查 the source code 中主要包含一个
spring.provides 文件:

provides: spring-boot-actuator,micrometer-core

我不知道以与 Spring Boot Starter 相同的方式处理的确切方法,但作为可能可接受的解决方法,您可以在您的 jar 中定义一个 @Configuration class指定 @ComponentScan("com.mylib").

 @Configuration
 @ComponentScan("com.mylib")
 public class MyLibConfig {
     //...
 }

这样jar的客户端需要"only"导入@Configuration class :

@Import(MyLibConfig.class)
@Configuration
public class ClientConfig{
  //...
}

您可以创建一个 Spring 引导启动程序,其样式与 Spring 提供的启动程序相同。它们本质上是一个带有 spring.factories 文件的 jar 库,该文件指向 @Configuration class 以加载那里的一些其他注释以提供 overriding/bean 后退(@ConditionalOnMissingBean) 并通常提供自己的 @ConfigurationProperties

Stéphane Nicoll 提供了关于如何构建一个的出色演示。

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

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

库方法也可以,但我认为不将其作为启动器没有任何好处。此外,对于任何 library/starter,我建议删除 @ComponentScan 并只在 @Configuration 中定义 bean。这将适用于像 @RestController 这样的刻板印象,如果你在配置中创建一个 @Bean 等,它将正常运行。