1 Problem Description

Writes a Component that uses the @Component and @ConfigurationProperties annotations internally to read configuration files in YML format. Because some initialization is required, the CommandLineRunner interface is implemented and initialized in the Run () method.

@Component @ConfigurationProperties(Prefix = "XXX ") Public Class DatasourceMapperConfig implements CommandLineRunner {...  @Override public void run(String... args) throws Exception { setDSGroupNames(); setDSNames(); valid(); log.debug("configs -> {}", configs); }... }Copy the code

When you jar this component and load it into the Spring Boot framework, CommandLineRunner’s run() is not running, so the initialized values are empty:

2 Cause Analysis

Because this class is packaged in a component, it is not automatically scanned. Even importing this class with the @import annotation in the Spring Boot Boot class does not work. Because the @import annotation is only valid for the @Component annotation. Unfortunately, Spring Boot has not found any comments related to the automatic scanning area out of CommandLineRunner.

3 Problem Solving

Since it is a configuration class, the Spring framework must execute the set method, so move the initialization code into the set method.

public void setConfigs(List<DatasourceConfig> configs) {
        this.configs = configs;
        setDSGroupNames();
        setDSNames();
        valid();
        log.debug("configs -> {}", configs);
}
Copy the code