Spring Boot

Add another module components to context

Scan components in all packages of a module

Supposing that the SecondApplicationConfiguration is the secondapplication application root Configuration class:

public class FirstApplication {

In this way, all the beans detected by the SecondApplicationConfiguration specified component scan will be registered in the FirstApplication context.

This approach is simple, but can create some hidden problems. For example, if there is a component in secondapplication which has dependencies in thirdapplication, we will have to add the ThirdApplicationConfiguration.class to @Import, even if the secondapplication component with such dependency is not used by the firstapplication. In order to avoid this problem, we can use a customized Configuration class precisely specifying the packages/class to add to the firstapplication context.

Scan components only in certain packages

A Configuration class specifying the secondapplication packages/classes to add to the application context:

  excludeFilters = {
    @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class),
    @ComponentScan.Filter(type = FilterType.ANNOTATION, value = SpringBootApplication.class),
    @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = "secondapplication.some.package.excluded.*"),
  basePackages = "secondapplication.some.package")
public class MyConfiguration {


  • secondapplication.some.package is the secondapplication root package containing either a SecondApplicationConfiguration or a SecondApplication class,
  • @ComponentScan specifies the secondapplication basePackage to start the components scan from, as well as a list of excludeFilters to filter out the scanned packages/classes,
  • secondapplication root application class with @SpringBootApplication annotation and root configuration class with @Configuration annotation should be excluded from the component scan. If we do not do this, either of them will add all the secondapplication components to the context no matter which other excludeFilters are present in the @ComponentScan,
  • FilterType.ASPECTJ component scan filter with pattern secondapplication.some.package.excluded.* excludes all the packages and classes of the secondapplication.some.package package,
  • @EnableJpaRepositories specifies a base package containing the repositories,
  • @EntityScan specifies a base package containing the entities.

Import the MyConfiguration class in the firstapplication @SpringBootApplication class:

public class FirstApplication {