This used to be the previous scenario.
@Bean
@ConfigurationProperties("database")
public DataSource database1DataSource() {
return DataSourceBuilder.create().build();
}
Now, to test SQL queries, I added this,
@Bean
@ConfigurationProperties("testdatabase")
public DataSource myperksTestDataSource() {
return DataSourceBuilder.create().build();
}
Similarly, I have created 2 methods each for PlatformTransactionManager
and SqlSessionFactory
. I realised that Spring-boot picks up SqlSessionFactory
and if I create two there will be a conflict and there will be an IllegalStateException
with Failed to load application context.
Situation :
I want to create two databases connection, one for production and another for integration testing. I have created configurations for each in application.yml
file. I want spring to pick up appropriate configurations.
What I tried
I annotated production beans with @Primary
. Which worked. I could get spring to run.
Problem
I do not use SqlSessionFactory
directly, Spring does. If I mark SqlSessionFactory
with primary and write another, it is of no use since no method is going to call it.
So, as a means of solution, I thought of conditionally assigning SqlSessionFactory
with different datasources. But, how would I identify that the run time is a test.
You don't need any Java configuration at all. Cut it all and simply provide a value in the SPRING_DATASOURCE_URL
environment variable when you start your application; Boot will construct and wire a DataSource
connected there.
simply create a application.yml with different profiles, like:
spring:
profiles: dev
datasource:
url: jdbc:h2DEV:mem;DB_CLOSE_ON_EXIT=FALSE
username: sa
password:
driverClassName: org.h2.Driver
spring:
profiles: integ
datasource:
url: jdbc:h2Integ:mem;DB_CLOSE_ON_EXIT=FALSE
username: sa
password:
driverClassName: org.h2.Driver
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.