package com.teda.z4.webApp;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Bean(name = "primary")
@ConfigurationProperties(prefix = "spring.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "second")
@ConfigurationProperties(prefix = "spring.second")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "cwht")
@ConfigurationProperties(prefix = "spring.cwht")
public DataSource cwhtDataSource() {
return DataSourceBuilder.create().build();
}
}
同一项目配置不同数据源的要点就是在properties通过配置不同的前缀的数据库连接,然后以上面的这种方式配置不同的数据库连接
package com.teda.z4.webApp;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.teda.z4.webApp.dao.primary"}, sqlSessionFactoryRef = "primaryFactory")
public class PrimaryConfig {
@Autowired
@Qualifier("primary")
private DataSource dataSource;
@Bean
@Primary
public SqlSessionFactory primaryFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
return factoryBean.getObject();
}
}
@MapperScan
是比较核心的一个注解,sqlSessionFactoryRef指定了使用了哪个数据库的sqlSession,basepackages配置了那个包下的使用这个sqlSession进行连接
网友评论