我想在应用程序中使用多个数据源(oracle和sqlserver)。 根据我已完成配置。 我所拥有的代码就像
配置文件
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfiguration {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.secondDasource")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(firstDataSource());
}
@Bean
public JdbcTemplate sJdbcTemplate() {
return new JdbcTemplate(secondDataSource());
}
}
application.yml文件
#First
spring.datasource.driverClassName: oracle.jdbc.driver.OracleDriver
spring.datasource.url: someJdbcUrl
spring.datasource.username: username
spring.datasource.password: password
#Second
spring.secondDatasource.driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.secondDatasource.url: some sqlUrl
spring.secondDatasource.username: username
spring.secondDatasource.password: password
主要课程
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class MainApp {
public static void main(String[] args) throws Exception {
SpringApplication.run(MainApp.class, args);
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(MainApp.class, args);
configurableApplicationContext.start();
String[] beanNames = configurableApplicationContext.getBeanDefinitionNames();
System.out.println("--------------------------------------");
System.out.println();
for (String beanName : beanNames) {
System.out
.println(beanName + " : " + configurableApplicationContext.getBean(beanName).getClass().toString());
}
System.out.println("--------------------------------------");
System.out.println();
}
}
gradle dependancies
compile group: 'sqljdbc4', name: 'sqljdbc4', version: '4.0'
compile(group: 'ojdbc14', name: 'ojdbc14', version: '10.2.0.5')
当我尝试使用第二个数据源时,它会抛出异常,因为它的bean尚未创建
我在这里失踪了什么?
答案 0 :(得分:0)
尝试通过bean名称注入:
@Bean
public JdbcTemplate jdbcTemplate(@Qualifier("firstDataSource") DataSource firstDataSource){
return new JdbcTemplate(firstDataSource);
}
@Bean
public JdbcTemplate sJdbcTemplate(@Qualifier("secondDataSource") DataSource secondDataSource){
return new JdbcTemplate(secondDataSource);
}