2

我有一个相当标准的 spring boot 应用程序,它是用几个 gradle 模块的 gradle 构建的。这是目录布局:

 - root
   - serviceA
     - src/main/java
       - org.example.serviceA
         - ServiceAApplication.java
   - serviceB
   - serviceC
   - common
     - src/main/java
       - org.example.common
         - CommonSecurityConfiguration.java

我想做的是将共享模块中的类包含在. 请注意,并驻留在不同的基础包中。CommonSecurityConfigurationcommonserviceAServiceAApplicationCommonSecurityConfiguration

我尝试@Import(CommonSecurityConfiguration.class)在 my上使用ServiceAApplication,但这根本没有明显的效果。

唯一有效的是这样注释ServiceAApplication

@SpringBootApplication(basePackages = { "org.example.serviceA", "org.example.common"})
public class ServiceAApplication { ... }

这种方法有效,但对我来说似乎非常粗略- 它会导入它在org.example.common.

有一个更好的方法吗?我可以通过一一列出单个类来将它们包含到组件扫描中吗?

4

3 回答 3

1

尝试使用配置类上面的@Import(CommonSecurityConfiguration.class)。所以它看起来像这样:

@Configuration
@Import(CommonSecurityConfiguration.class)
public class ServiceAConfiguration { ... }
于 2020-02-06T15:22:02.397 回答
1

我相信您正在寻找的是@CompnentScan("com.example"),这将告诉 Spring 以递归方式查看指定路径下的所有文件。(在这种情况下,它将是@ComponentScan("root")

您可以在此处找到更多信息:baeldun.com/spring-component-scanning

希望这可以帮助。

于 2020-02-06T15:26:29.533 回答
0

既然要控制引入哪些组件,我们可以做一个注解,我们称这个注解为 PickyComponentImport

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PickyComponentImport{

} 

然后在我们的 SpringBootApplication 注解上,我们可以添加一个新的过滤器来寻找这个注解。

@ComponentScan(basePackages = { "org.example.serviceA",
        "org.example.common" }, includeFilters = @Filter(PickyComponentImport.class))
public class ServiceAApplication { ... }

然后我们可以在我们想要包含的任何类上添加该注释

@Configuration
@PickyComponentImport
public class CommonSecurityConfiguration {

}

编辑:我认为如果您采用这种方法,您可以将 componentScan basepackage 作为 root。

于 2020-02-07T02:33:38.490 回答