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.