简体   繁体   English

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

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

I want to use some classes that exist inside another spring boot application. 我想使用另一个Spring Boot应用程序中存在的一些类。 How can I import them whitout loading all it's beans in my application. 我如何导入它们,而不是在应用程序中加载所有bean。

The @ComponentScan annotation is responsible for automatically loading any classes marked with @Component or its derived annotations. @ComponentScan注释负责自动加载标有@Component或其派生注释的所有类。 This annotation has various options to filter which beans are loaded. 该注释具有各种选项来过滤加载了哪些bean。

If the parent package of the imported application is different from that of your main application, you can simply set the basePackages option to a specific parent package. 如果导入的应用程序的父程序包与主应用程序的父程序包不同,则只需将basePackages选项设置为特定的父程序包。

For example, say that your main application has the package com.example.main and the imported application has com.example.imported , you can put in: 例如,假设您的主应用程序具有com.example.main包,而导入的应用程序具有com.example.imported ,则可以输入:

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

This will import only beans defined under the main application package. 这将仅导入在主应用程序包下定义的bean。

If this is not enough, you can also use the excludeFilters option on the same annotation. 如果这还不够,还可以在同一注释上使用excludeFilters选项。

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

You can also combine both options for more specific filtering. 您也可以将两个选项组合在一起以进行更具体的过滤。

@metacubed answer is probably sufficient. @metacubed答案可能就足够了。 But another very simple approach would be to use @ComponentScan(basePackageClasses = {BeansToExport.class, MoreBeansToExport.class, ...}) - Example: 但是另一种非常简单的方法是使用@ComponentScan(basePackageClasses = {BeansToExport.class, MoreBeansToExport.class, ...}) -示例:

@Configuration
public class BeansToExport {

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

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

}

I would call this an inclusive strategy, whereas @metacube's example would be an exclusive strategy. 我将其称为包容性策略,而@metacube的示例将是一个专有策略。 Both have their uses. 两者都有其用途。

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

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