springboot 配置多个jndi数据源
1.在application.properties中,添加jndi配置
如下图
2.新建dataSourceConfig类
3.dataSourceConfig类详细代码
这里只贴出其中一个,多个数据源类似配置,只需更改 basePackages 路径和 @Value("${spring.datasource.source1.jndi-name}"),以及下面名称带test1前缀的地方,不要和其他dataSourceConfig重名
@Configuration //注册到springboot 容器中 @MapperScan(basePackages = "对应的Mapper包路径",sqlSessionTemplateRef = "test1SqlSessionTemplate") public class DataSource1Config { //application.properties中的jndi名称 @Value("${spring.datasource.source1.jndi-name}") private String jndiName; @Bean(name = "test1DataSource",destroyMethod = "") // destroy method is disabled for Weblogic update app ability @ConfigurationProperties(prefix = "spring.datasource.bigdata") public DataSource bigdataDs() throws NamingException { JndiObjectFactoryBean bean=new JndiObjectFactoryBean(); bean.setJndiName(jndiName); bean.setProxyInterface(DataSource.class); bean.setLookupOnStartup(false); bean.afterPropertiesSet(); return (DataSource) bean.getObject(); } @Bean(name = "test1SqlSessionFactory") public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //加载其他文件,如mapper.xml // bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); return bean.getObject(); } //事务管理 @Bean(name = "test1TransactionManager") public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "test1SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
4.打开tomcat目录下context.xml文件
添加以下配置,多个数据源写多个Resource即可,注意name需要和application.properties配置的名称一致
<Resource name="jdbc/数据库名称" auth="Container" type="javax.sql.DataSource" maxTotal="100" maxIdle="30" maxWaitMillis="10000" username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/javatest"/>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_37030399/article/details/103405993