0

I'm trying to make a very simple autoconfiguration for a usage of Togglz state repository for a database. I want to have a JDBCStateRepository when there a DataSource bean available and keep the default one when running test excluding database or any case like that.

This is a very simple spring boot application with a database connection and the togglz library.

@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class TogglzStateRepositoryAutoConfiguration {
    
    @Bean
    @ConditionalOnBean(DataSource.class)
    public StateRepository getStateRepository(DataSource dataSource) {
        return new JDBCStateRepository(dataSource);
    }
}

The problem is that this bean is NEVER created using this configuration, it never find the DataSource:

   TogglzStateRepositoryAutoConfiguration#getStateRepository:
      Did not match:
         - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans of type javax.sql.DataSource (OnBeanCondition)

When a few rows above in the report:

DataSourceHealthContributorAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'org.springframework.jdbc.core.JdbcTemplate', 'org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource' (OnClassCondition)
      - @ConditionalOnEnabledHealthIndicator management.health.defaults.enabled is considered true (OnEnabledHealthIndicatorCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found bean 'dataSource' (OnBeanCondition)

And this regardless of the configuration order that I put (@DependsOn, @AutoConfigureAfter, Before etc).

Any idea of what I could do or test to have this working as expected, or explain me what I missed?

Thank you !

Emilien
  • 106
  • 9

1 Answers1

0

Ok I found the answer, Spring is not managing @Configuration and AutoConfiguration the same way (even if they are sharing the same annotation).

Difference is that you have to declare an AutoConfiguration from the spring.factories file like:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
xxx.xxx.xxx.TogglzStateRepositoryAutoConfiguration

Then it will process the bean declaration inside it differently to take into account the proper annotation and injection order.

Hope it may help !

Emilien
  • 106
  • 9