Spring 引导组件扫描仅包括特定包

Spring Boot component scan include only specific package

我有两个 Spring Boot 项目,我们称它们为 FooBarBar 作为依赖包含在 Foo 中。现在我只想在 FooComponent Scan 中包含来自 Bar 的特定包(比方说:com.example.bar.ctrl)。我知道您可以通过 excludeFilters 排除包,但这会花费更多的精力,而且每次在 Bar 中创建新包时我都需要维护 exclude filter-list。 归档该行为的最佳方法是什么?

如果您正在使用 @ComponentScan 注释,那么它有一个 basePackages 属性,该属性需要扫描 String[] 个包。

我会这样做:

1) Foo 包将包含 com.example.foo 下的所有 bean,并且 @SpringBootApplication main class 将在该包中,因此它将扫描 [=10= 中的所有 bean ] 包。

2) 在 bar package com.example.bar.ctrl 中,我会创建 @Configuration with @ComponentScan annotation 没有任何属性,所以它只会扫描 ctrl package + subpackages。

3) 我将从点 2) @Import 配置 class 到点 1) class

@ComponentScanincludeexclude 属性不需要显式包。