• springBoot配置双数据源


    spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/compstore2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    spring.datasource.primary.username=root
    spring.datasource.primary.password=123456
    #第二个数据库
    spring.datasource.second.jdbc-url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    spring.datasource.second.username=root
    spring.datasource.second.password=123456
    
    package com.ustcinfo.fn.config;
    
    import org.springframework.beans.factory.annotation.Autowired;
    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 org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
    
    import javax.annotation.Resource;
    import javax.sql.DataSource;
    
    /**
     * @author Jamin
     * @date 2020/12/26 14:06
     * 双数据源配置
     */
    @Configuration
    public class DataSourceConfig {
    	@Bean
    	@Primary
    	@ConfigurationProperties(prefix = "spring.datasource.primary")
    	public DataSource primaryDataSource() {
    		return DataSourceBuilder.create().build();
    	}
    
    	@Bean
    	@Primary
    	public JdbcTemplate primaryJdbcTemplate(@Autowired DataSource dataSource) {
    		return new JdbcTemplate(dataSource);
    	}
    
    	@Bean
    	@Primary
    	public NamedParameterJdbcTemplate primaryNamedParameterJdbcTemplate(@Autowired DataSource dataSource) {
    		return new NamedParameterJdbcTemplate(dataSource);
    	}
    
    
    	@Bean(name = "secondDataSource")
    	@ConfigurationProperties(prefix = "spring.datasource.second")
    	public DataSource secondDataSource() {
    		return DataSourceBuilder.create().build();
    	}
    
    	@Bean(name = "secondJdbcTemplate")
    	public JdbcTemplate secondJdbcTemplate(@Qualifier("secondDataSource") DataSource dataSource) {
    		return new JdbcTemplate(dataSource);
    	}
    
    
    }
    
    作者: JaminYe
    版权声明:本文原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
  • 相关阅读:
    【SQLSERVER】动态游标的实现
    【Oracle】动态游标的实现
    【SQLSERVER】拷贝表数据
    LeetCode: Count and Say
    LeetCode: Construct Binary Tree from Preorder and Inorder Traversa
    LeetCode: Combinations
    LeetCode: Convert Sorted List to Binary Search Tree
    LeetCode: Decode Ways
    LeetCode: Combination Sum II
    LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
  • 原文地址:https://www.cnblogs.com/JaminYe/p/14370365.html
Copyright © 2020-2023  润新知