带有依赖项且不带@ComponentScan的Spring Boot自动配置 [英] Spring boot auto configuration with dependency and without @ComponentScan

本文介绍了带有依赖项且不带@ComponentScan的Spring Boot自动配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring boot提供了 @ComponentScan 查找要扫描的软件包.

Spring boot provides @ComponentScan to find packages to be scanned.

我正在构建一个库,其中包含 @RestControllers package com.mylib.controller .在不同的程序包中还有其他带有构造型注释的类.

I am building a library which has @RestControllers inside with package com.mylib.controller. There are other classes as well with stereotype annotations in different packages.

因此,如果有人正在使用 com.myapp 基本软件包开发SpringBoot应用程序.他在他的应用程序中使用了我的图书馆.他需要提及 @ComponentScan("com.mylib")来发现库的原型组件.

So, if some one is developing SpringBoot Application with com.myapp base package. He uses my library in his application. He need to mention @ComponentScan("com.mylib") to discover stereotype components of library.

是否有任何方法可以扫描组件而不在 @ComponentScan 中包含库包?

Is there any way to scan components without including library package in @ComponentScan?

spring-boot-starter-actuator 暴露其端点时就具有依赖性,而不定义 @ComponentScan .或任何扫描的默认程序包,而与应用程序基本程序包无关.

As spring-boot-starter-actuator expose its endpoints just with dependency, without defining @ComponentScan. OR any default package which is scanned regardless of application base package.

推荐答案

您可以使用与Spring提供的启动器相同的样式来创建Spring Boot Starter.它们本质上是一个jar库,带有一个 spring.factories 文件,该文件指向 @Configuration 类,以在其中加载一些其他注释以提供覆盖/bean退避( @ConditionalOnMissingBean ),通常会提供自己的 @ConfigurationProperties .

You could create a Spring Boot Starter in the same style as the Spring Provided Starters. They are essentially a jar'd library with a a spring.factories file pointing to the @Configuration class to load with some other annotations on there to provide overriding/bean back off (@ConditionalOnMissingBean) and generally provide their own @ConfigurationProperties.

斯特凡·尼科尔(StéphaneNic​​oll)提供了一个出色的演示,演示如何建造一个.

Stéphane Nicoll provided an excellent demo of how to build one.

https://github.com/snicoll-demos/hello-service-自动配置

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

It is also documented in the Spring Boot documentation. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html

库方法也可以工作,但是我认为不将其作为入门者没有任何好处.另外,对于任何库/启动器,我建议删除 @ComponentScan 并仅在 @Configuration 中定义bean.这将适用于诸如 @RestController 等构造型.如果您在配置中从中创建 @Bean ,它将正常工作.

The library approach would also work but I see no benefit in not making it a starter. Additionally for any library/starter I'd recommend dropping the @ComponentScan and just defining the beans in a @Configuration. This will work for sterotypes like @RestController etc. will function as normal if you create an @Bean out of it in a configuration.

这篇关于带有依赖项且不带@ComponentScan的Spring Boot自动配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆