In my Spring Boot project, I have used Maven multi-module to organize the project structure. I have placed the database configuration in the common-db module and designed a DataBaseProperties class to add new functionality to the default database configuration in Spring Boot.
@Configuration
@ConfigurationProperties("spring.datasource")
@Getter
@Setter
@ToString
@FieldDefaults(level = AccessLevel.PRIVATE)
@Slf4j
public class DataBaseProperties implements InitializingBean {
String driverClassName = "com.mysql.cj.jdbc.Driver";
Integer initialSize;
Integer maxActive;
Integer minIdle;
Integer maxWait;
Boolean showSql = false;
String basePackage = "com.example.**.mapper";
String[] mapperLocations;
Boolean cacheEnabled = true;
@Override
public void afterPropertiesSet() {
log.info("configuration properties: {}", this);
}
}
In the common-db module, I use spring.factories to inject the Bean:
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.common.db.config.properties.DataBaseProperties
Then I import this common-db module into the main project. However, I found that DataBaseProperties cannot retrieve the configuration information.
I tried modifying the configuration prefix to example.datasource, but it didn't work. I also tried using @EnableConfigurationProperties to inject ConfigurationProperties, but the problem remained unresolved, and I'm not sure if it's due to incorrect usage or other reasons.
I also attempted to add the following Maven dependency, but it had no effect.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
After debugging, I found that during the initialization of DataBaseProperties, the BeanFactory is missing ConfigurationPropertiesBindingPostProcessor, which prevents it from obtaining the configuration information. However, I have written other @ConfigurationProperties classes that can retrieve the configuration information and have ConfigurationPropertiesBindingPostProcessor during initialization.
By observing the List<BeanPostProcessor> beanPostProcessors field in AbstractBeanFactory, I found that DataBaseProperties is using AnnotationConfigServletWebServerApplicationContext, while other ConfigurationProperties classes that can retrieve the configuration information use AnnotationConfigApplicationContext. There may be other ApplicationContext being used, but what I can confirm is that AnnotationConfigServletWebServerApplicationContext lacks ConfigurationProperties.
Now, I'm not sure why this PostProcessor is missing. Maybe it has always been missing? I hope someone can help me make the ConfigurationProperties class in my common-db module retrieve the configuration. I appreciate any help and thank you for reading this.