0

I have the strangest of the situations when configuring two DataSources in my Spring Boot app that was working OK with only one:

@Configuration
(...)
    @Bean(destroyMethod = "close")
    protected DataSource applicationDataSource(
        (...)
        return dataSource;
    }

and with two:

@Configuration
(...)
    @Bean(destroyMethod = "close")
    @Primary
    protected DataSource applicationDataSource(
        (...)
        return dataSource;
    }

@Configuration
(...)
    @Bean
    protected DataSource localDataSource(
        (...)
        return dataSource;
    }

(they are in different configuration files)

Now the strange thing is that with two DS there is no related specific error. The error I get is a seemingly unrelated error saying it can't find a Injected bean instance (in a completely different configuration file that has nothing to do with DataSources). I did notice that when using only one DS that DS bean is instantiated well before the bean that shows in the error, which makes me think that when defining two DS they simply are ignored.

I tried lots of things, including declaring the second bean as another type of DS

@Configuration
(...)
    @Bean
    protected HikariDataSource localDataSource(
        (...)
        return dataSource;
    }

but nothing worked.

Now for the strangest thing, I found out a hack that works, by declaring the second bean as a Object(!!!)

@Configuration
(...)
    @Bean
    protected Object localDataSource(
        (...)
        return dataSource;
    }

This works!!! I just have to cast it elsewhere (implementing a SqlSessionFactoryBean or DataSourceTransactionManager for instance).

Note that the methods are protected but I tested with public as well. As for the Spring Boot app I tested both with or without exclusion

@Configuration
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})

So I got it working and all is well, but I can't figure how the heck this is happening and I wold really like to make it work without hacks...

Cheers.

amsmota
  • 171
  • 2
  • 11

1 Answers1

0

I suspect you have an autowiring issue due to having two beans of type DataSource configured, possibly with more than one marked with @Primary

Turning on logging for org.springframework should highlight this. Post the start up log.

Your fix works because you are in effect creating only one bean of type DataSource, so the autowiring issue gets resolved.

PaulNUK
  • 4,774
  • 2
  • 30
  • 58