SoFunction
Updated on 2025-04-12

Interpretation of why SpringBoot uses DeferredImportSelector

DeferredImportSelectorIt was introduced in Spring Framework 3.1ImportSelectorAn enhanced version of the interface is mainly used to delay loading configuration classes and improve the startup speed of Spring Boot applications.

It allows some configuration classes to be optionally imported based on the information of other configuration classes after all configuration classes are processed.

Why use DeferredImportSelector?

TraditionalImportSelectorThis is performed in the early stages of configuration class resolution, which means that when selecting the configuration class to be imported, it may not have access to the full configuration information, resulting in the failure to make the best choice.

DeferredImportSelectorBy solving this problem, its execution will be delayed until all regular configuration classes are processed, at which point it can access information of all configuration classes, making smarter import decisions.

How DeferredImportSelector works

register:When Spring container parses the configuration class, if a class is found to be implementedDeferredImportSelectorinterface, it won't execute immediatelyselectImports()Method, insteadDeferredImportSelectorRegister an instance to aDeferredImportSelectorHandlermiddle.

Delayed execution:After all configuration classes are processed,DeferredImportSelectorHandlerWill be responsible for performing all registrationsDeferredImportSelector

Grouping and sorting (optional): DeferredImportSelectorCan be achievedInterface, multipleDeferredImportSelectorGroup and sort by group. Spring Boot allowsSorting to control the execution order.

selectImports()method:existselectImports()In the method,DeferredImportSelectorYou can access the configuration information of the entire Spring container, for example:

  • Registered Bean definition.
  • The configuration class that has been loaded.
  • Environment information (Environment).

Returns the configuration class to be imported: selectImports()The method returns a String array containing the fully qualified name of the configuration class to be imported. Spring containers import corresponding configuration classes based on these fully qualified names and register beans.

Advantages of DeferredImportSelector

  • Lazy loading:Avoid loading unnecessary configuration classes prematurely and improve startup speed.
  • Smarter configuration options:Make more accurate configuration choices based on loaded configuration information.
  • Conditional configuration:Implement more complex conditional configuration logic.
  • Sort and group:controlDeferredImportSelectorexecution order.

Disadvantages of DeferredImportSelector

  • More complex:CompareImportSelectorMore complex, it requires understanding the mechanisms of lazy loading and grouping sorting.
  • Debugging difficulty increases:Since it is delayed execution, more steps may be required during debugging.

DeferredImportSelector usage scenarios

  • Automatic configuration:Spring Boot's automatic configuration mechanism is widely usedDeferredImportSelector. For example,EnableAutoConfigurationAnnotation usageAutoConfigurationImportSelectorTo select the automatic configuration class to be imported.
  • Conditional configuration:Select whether to import a configuration class based on whether a bean exists or the value of a configuration property.
  • Modular:Decompose the application into multiple modules and select the configuration to import other modules based on the loaded module information.

Example of DeferredImportSelector

import ;
import ;

public class MyDeferredImportSelector implements DeferredImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // You can get annotation information importingClassMetadata        // You can access the Bean definition in the Spring container
        // Select to import different configuration classes according to the conditions        if (conditionA()) {
            return new String[] { "" };
        } else {
            return new String[] { "" };
        }
    }

    private boolean conditionA() {
        // Implement conditional logic        return true; // Example: Always return true    }
}

Example: Grouping and sorting

import ;
import ;

import ;
import ;
import ;

public class MyDeferredImportSelector implements DeferredImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{""};
    }

    @Override
    public Class<? extends Group> getImportGroup() {
        return ;
    }

    public static class MyGroup implements Group {

        private final List<Entry> entries = new ArrayList<>();

        @Override
        public void process(AnnotationMetadata metadata, DeferredImportSelector importSelector) {
            // You can decide whether to add an entry based on the information of metadata and importSelector            (new Entry(metadata, (metadata)));
        }

        @Override
        public Iterable<Entry> selectImports() {
            // Return a list of classes that need to be imported. Here you can sort entries to control the order of imports            return entries;
        }
    }
}

How to use DeferredImportSelector

  • accomplishDeferredImportSelectorinterface: Create a class and implement itDeferredImportSelectorInterface and rewriteselectImports()method.
  • accomplishgetImportGroup()Method (optional): If grouping and sorting are required, then implementgetImportGroup()And return an implementationGroupThe class of the interface.
  • registerDeferredImportSelector: Can be passed@ImportAnnotation, or inMETA-INF/Register in the fileDeferredImportSelector

Applications in Spring Boot Auto-configuration

Spring Boot's automatic configuration mechanism utilizationDeferredImportSelectorDelay loading and conditional configuration are implemented.

  • @EnableAutoConfigurationannotation:This annotation triggers the automatic configuration mechanism.
  • AutoConfigurationImportSelector: @EnableAutoConfigurationWill use it eventuallyAutoConfigurationImportSelectorthisDeferredImportSelector
  • document: AutoConfigurationImportSelectorfromMETA-INF/Read in the fileList of automatic configuration classes corresponding to the key.
  • Conditional filtering: AutoConfigurationImportSelectorThese automatic configuration classes are filtered based on conditions in the Spring container (for example, whether there is a bean or the value of a configuration property), and only automatic configuration classes that meet the criteria are selected for import.

Summarize

DeferredImportSelectorIt is an important feature in Spring Boot, which allows delayed loading and conditional configurations to improve application startup speed and flexibility.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.