springboot多數據源(oracle、mysql)

一、application.properties配置: html

server.port=8085
server.tomcat.uri-encoding=utf-8





#MySQL
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test_spboot?characterEncoding=utf8
spring.datasource.primary.username=root
spring.datasource.primary.password=123456

#oracle
spring.datasource.secondary.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.secondary.jdbc-url=jdbc:oracle:thin:@127.0.0.1:1521:XE
spring.datasource.secondary.username=user01
spring.datasource.secondary.password=user01


#視圖層控制
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**

2DataSourceConfig.javajava

package com.configuration;

import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {
    @Bean(name = "primaryDataSource")
//    @Qualifier("primaryDataSource")//原博主這裏加上@Qualify 沒有必要 刪了也沒有影響
    @ConfigurationProperties("spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "secondaryDataSource")
//    @Qualifier("secondaryDataSource") //原博主這裏加上@Qualify 沒有必要 刪了也沒有影響
    @ConfigurationProperties("spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }



    /**
     * @param dataSource
     * @return
     * @Bean明確地指示了一種方法,什麼方法呢——產生一個bean的方法, 而且交給Spring容器管理;從這咱們就明白了爲啥@Bean是放在方法的註釋上了,
     * 由於它很明確地告訴被註釋的方法,你給我產生一個Bean,而後交給Spring容器,
     * 實現依賴注入
     */
    @Bean(name = "primaryJdbcTemplate")
    public JdbcTemplate primaryTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}

3使用:mysql

@Autowired
private JdbcTemplate secondaryJdbcTemplate
相關文章
相關標籤/搜索