Spring Download: Conditional Database Type

I have a Spring boot application and want to implement specific repository implementations based on the type of the underlying SQL data source (defined using the spring.datasource. * Properties).

I tried using the conditional condition here, but unfortunately when it is evaluated, I cannot get the data source to check the type of database.

My current state is as follows:

@Order(Ordered.LOWEST_PRECEDENCE - 10)
class OnDatabaseTypeCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

        DataSource dataSource = context.getBeanFactory().getBean(DataSource.class);
        // further matching code here

}

It should be used something like this:

@ConditionalOnDatabaseType(H2)
public class MyCustomImplementation implements MyRepository {
    // Code
}

However, when the condition is evaluated, I get an exception that the data source is not defined:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:348)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:335)

, , , beans. , Spring, , ? Spring?

, , : , (, H2) , . , , . , JDBC Spring, ( org.springframework.jdbc.support.JdbcUtils).

+4
1

bean. bean, , bean . .

, ( ) . Spring Boot , DataSource, .

, , , bean, (@AutoconfigureAfter). , . OnBeanCondition, , Spring Boot . , , .

, . , , , .

+2

Source: https://habr.com/ru/post/1658684/


All Articles