繁体   English   中英

导入其他没有它的bean的Spring Boot应用程序

[英]Import other Spring Boot application without it's beans

我想使用另一个Spring Boot应用程序中存在的一些类。 我如何导入它们,而不是在应用程序中加载所有bean。

@ComponentScan注释负责自动加载标有@Component或其派生注释的所有类。 该注释具有各种选项来过滤加载了哪些bean。

如果导入的应用程序的父程序包与主应用程序的父程序包不同,则只需将basePackages选项设置为特定的父程序包。

例如,假设您的主应用程序具有com.example.main包,而导入的应用程序具有com.example.imported ,则可以输入:

@ComponentScan(basePackages = {"com.example.main"})

这将仅导入在主应用程序包下定义的bean。

如果这还不够,还可以在同一注释上使用excludeFilters选项。

@ComponentScan(excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Imported.class)
})

您也可以将两个选项组合在一起以进行更具体的过滤。

@metacubed答案可能就足够了。 但是另一种非常简单的方法是使用@ComponentScan(basePackageClasses = {BeansToExport.class, MoreBeansToExport.class, ...}) -示例:

@Configuration
public class BeansToExport {

   @Bean
   public ServiceClass serviceClassBean(){
      return new ServiceClass();
   }

   @Bean
   public RespositoryClass repositoryClassBean(){
      return new RepositoryClass();
   }

}

我将其称为包容性策略,而@metacube的示例将是一个专有策略。 两者都有其用途。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM