springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解

文件在E:\学习文档子目录压缩\框架\springboot\代码\springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解

我的网盘\我的笔记\学习文档子目录压缩\框架\springboot\代码\springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解

 

定义多个数据源类需要注意的地方

1. @ConfigurationProperties(prefix = "spring.datasource.test1"

prefix前缀属性

/**

     * //可以点进@ConfigurationProperties 看下描述 如下这个 prefiX的值是.properties如果是默认即在

     * src/main/resources下的定义数据源的application.properties 的前缀 spring.datasource.test1.driver-class-name= com.mysql.jdbc.Driver

     * sprinboot默认前缀是 spring.datasource

     * * The name prefix of the properties that are valid to bind to this object. Synonym

     * for {@link #prefix()}.

     * @return the name prefix of the properties to bind

     * */

    @ConfigurationProperties(prefix = "spring.datasource.test1")  

    public DataSource testDataSource() {

       return DataSourceBuilder.create().build();

    }

 

2. @Primary 注解

@Configuration // 注册到springboot容器中

@MapperScan(basePackages = "com.xiangshuai.user1mapper", sqlSessionFactoryRef = "test1SqlSessionFactory")

public class DataSource1Config {

 

    /**

     * 注意

     * springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解

     * 这里只有 test1数据源类的方法下加@Primary注解,在DataSource2ConfigDataSource3Config

     * 数据源类的方法上均不加@Primary注解

     * @methodDesc: 功能描述:(配置test1数据库)

     * @author: LQX

     * @param: @return

     * @returnType:@return DataSource

     */

    @Bean(name = "test1DataSource")

    @Primary

    /**

     * //可以点进@ConfigurationProperties 看下描述 如下这个 prefiX的值是.properties如果是默认即在

     * src/main/resources下的定义数据源的application.properties 的前缀 spring.datasource.test1.driver-class-name= com.mysql.jdbc.Driver

     * sprinboot默认前缀是 spring.datasource

     * * The name prefix of the properties that are valid to bind to this object. Synonym

     * for {@link #prefix()}.

     * @return the name prefix of the properties to bind

     * */

    @ConfigurationProperties(prefix = "spring.datasource.test1")  

    public DataSource testDataSource() {

       return DataSourceBuilder.create().build();

    }

 

如果定义的数据源类有多个加了@Primary 会报如下异常

No qualifying bean of type [javax.sql.DataSource] is defined: more than one 'primary' bean found among candidates: [test1DataSource, test3DataSource, test2DataSource]

 

 

 

项目结构

 

App.app

package com.xiangshuai.app;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.context.annotation.ComponentScan;

 

/**

 * @author lqx

 * 项目在

 *E:\学习文档子目录压缩\框架\springboot\代码\springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解\springboot-mybatis.rar

 或

 我的网盘\我的笔记\学习文档子目录压缩\框架\springboot\代码\springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解\springboot-mybatis.rar

 */

@ComponentScan(basePackages = "com.xiangshuai")

@EnableAutoConfiguration

public class App {

         public static void main(String[] args) {

                  SpringApplication.run(App.class, args);

         }

 

}

 

 

UserController.java

package com.xiangshuai.controller;

 

import java.util.List;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

 

import com.xiangshuai.pojo.User;

import com.xiangshuai.user1mapper.User1Mapper;

import com.xiangshuai.user2mapper.User2Mapper;

import com.xiangshuai.user3mapper.User3Mapper;

 

@RestController

public class UserController {

         @Autowired

         User1Mapper user1Mapper;

        

         @Autowired

         User2Mapper user2Mapper;

        

         @Autowired

         User3Mapper user3Mapper;

        

         @RequestMapping("/getUsers1")

     public List<User> getUsers1(String name){

                  return user1Mapper.findByNameLike(name);

     }

         @RequestMapping("/getUsers2")

         public List<User> getUsers2(String name){

                  return user2Mapper.findByNameLike(name);

         }

        

         @RequestMapping("/addUser1")

         public int addUser1(){

                  return user1Mapper.insert("刘小三", 19);

         }

        

        

         @RequestMapping("/addUser2")

         public int addUser2(){

                  return user2Mapper.insert("刘小三", 19);

         }

        

        

 

         @RequestMapping("/getUsers3")

     public List<User> getUsers3(String name){

                  return user3Mapper.findByNameLike(name);

     }

        

}

 

DataSource1Config.java

package com.xiangshuai.datasource;

 

import javax.sql.DataSource;

 

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.SqlSessionTemplate;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;

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.datasource.DataSourceTransactionManager;

 

@Configuration // 注册到springboot容器中

@MapperScan(basePackages = "com.xiangshuai.user1mapper", sqlSessionFactoryRef = "test1SqlSessionFactory")

public class DataSource1Config {

 

         /**

          * 注意

          * springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解

          * 这里只有 在test1数据源类的方法下加@Primary注解,在DataSource2Config,DataSource3Config

          * 数据源类的方法上均不加@Primary注解

          * @methodDesc: 功能描述:(配置test1数据库)

          * @author: LQX

          * @param: @return

          * @returnType:@return DataSource

          */

         @Bean(name = "test1DataSource")

         @Primary

         /**

          * //可以点进@ConfigurationProperties 看下描述 如下这个 prefiX的值是.properties如果是默认即在

          * src/main/resources下的定义数据源的application.properties 的前缀 spring.datasource.test1.driver-class-name= com.mysql.jdbc.Driver

          * sprinboot默认前缀是 spring.datasource

          * * The name prefix of the properties that are valid to bind to this object. Synonym

          * for {@link #prefix()}.

          * @return the name prefix of the properties to bind

          * */

         @ConfigurationProperties(prefix = "spring.datasource.test1")  

         public DataSource testDataSource() {

                  return DataSourceBuilder.create().build();

         }

 

         /**

          *

          * @methodDesc: 功能描述:(test1 sql会话工厂)

          * @author: LQX

          * @param: @param

          *             dataSource

          * @param: @return

          * @param: @throws

          *             Exception

          * @returnType:@param dataSource

          * @returnType:@return

          * @returnType:@throws Exception SqlSessionFactory

          */

         @Bean(name = "test1SqlSessionFactory")

         @Primary

         public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)

                          throws Exception {

                  SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

                  bean.setDataSource(dataSource);

//              bean.setMapperLocations(

//                                new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));

                  return bean.getObject();

         }

 

         /**

          *

          * @methodDesc: 功能描述:(test1 事物管理)

          * @author: LQX

          * @param: @param

          *             dataSource

          * @param: @return

          * @param: @throws

          *             Exception

          * @returnType:@param dataSource

          * @returnType:@return

          * @returnType:@throws Exception SqlSessionFactory

          */

         @Bean(name = "test1TransactionManager")

         @Primary

         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);

         }

 

}

 

DataSource2Config.java

package com.xiangshuai.datasource;

 

import javax.sql.DataSource;

 

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.SqlSessionTemplate;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;

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.datasource.DataSourceTransactionManager;

 

@Configuration // 注册到springboot容器中

@MapperScan(basePackages = "com.xiangshuai.user2mapper", sqlSessionFactoryRef = "test2SqlSessionFactory")

public class DataSource2Config {

         /**

          * 注意

          * springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加注解

          * 这里只有 在test1数据源类的方法下加注解,在DataSource2Config,DataSource3Config

          * 数据源类的方法上均不加注解

          * @methodDesc: 功能描述:(配置test2数据库)

          * @author: LQX

          * @param: @return

          * @returnType:@return DataSource

          */

         @Bean(name = "test2DataSource")

         @ConfigurationProperties(prefix = "spring.datasource.test2")

         public DataSource testDataSource() {

                  return DataSourceBuilder.create().build();

         }

 

        

        

         @Bean(name = "test2SqlSessionFactory")

         public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)

                          throws Exception {

                  SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

                  bean.setDataSource(dataSource);

//              bean.setMapperLocations(

//                                new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));

                  return bean.getObject();

         }

 

         /**

          *

          * @methodDesc: 功能描述:(test2 事物管理)

          * @param: @param

          *             dataSource

          * @param: @return

          * @param: @throws

          *             Exception

          * @returnType:@param dataSource

          * @returnType:@return

          * @returnType:@throws Exception SqlSessionFactory

          */

         @Bean(name = "test2TransactionManager")

         public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {

                  return new DataSourceTransactionManager(dataSource);

         }

 

         @Bean(name = "test2SqlSessionTemplate")

         public SqlSessionTemplate testSqlSessionTemplate(

                          @Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

                  return new SqlSessionTemplate(sqlSessionFactory);

         }

 

}

 

 

DataSource3Config.java

package com.xiangshuai.datasource;

 

import javax.sql.DataSource;

 

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.SqlSessionTemplate;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;

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.datasource.DataSourceTransactionManager;

 

@Configuration // 注册到springboot容器中

@MapperScan(basePackages = "com.xiangshuai.user3mapper", sqlSessionFactoryRef = "test3SqlSessionFactory")

public class DataSource3Config {

 

         /**

          * 注意

          * springboot多数据源需要注意定义数据源类的方法事有且只有一个数据源类的方法需加@Primary注解

          * 这里只有 在test1数据源类的方法下加@Primary注解,在DataSource2Config,DataSource3Config

          * 数据源类的方法上均不加@Primary注解

          * @methodDesc: 功能描述:(配置test1数据库)

          * @author: LQX

          * @param: @return

          * @returnType:@return DataSource

          */

         @Bean(name = "test3DataSource")

         @ConfigurationProperties(prefix = "spring.datasource.test3")

         public DataSource testDataSource() {

                  return DataSourceBuilder.create().build();

         }

 

 

         /**

          *

          * @methodDesc: 功能描述:(test3 sql会话工厂)

          * @author: LQX

          * @param: @param

          *             dataSource

          * @param: @return

          * @param: @throws

          *             Exception

          * @returnType:@param dataSource

          * @returnType:@return

          * @returnType:@throws Exception SqlSessionFactory

          */

         @Bean(name = "test3SqlSessionFactory")

         public SqlSessionFactory testSqlSessionFactory(@Qualifier("test3DataSource") DataSource dataSource)

                          throws Exception {

                  SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

                  bean.setDataSource(dataSource);

//              bean.setMapperLocations(

//                                new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));

                  return bean.getObject();

         }

 

         /**

          *

          * @methodDesc: 功能描述:(test3 事物管理)

          * @param: @param

          *             dataSource

          * @param: @return

          * @param: @throws

          *             Exception

          * @returnType:@param dataSource

          * @returnType:@return

          * @returnType:@throws Exception SqlSessionFactory

          */

         @Bean(name = "test3TransactionManager")

         public DataSourceTransactionManager testTransactionManager(@Qualifier("test3DataSource") DataSource dataSource) {

                  return new DataSourceTransactionManager(dataSource);

         }

 

         @Bean(name = "test3SqlSessionTemplate")

         public SqlSessionTemplate testSqlSessionTemplate(

                          @Qualifier("test3SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

                  return new SqlSessionTemplate(sqlSessionFactory);

         }

 

}

 

 

User.java

package com.xiangshuai.pojo;

 

public class User {

    private String name;

    private Integer age;

   

   

   

    public User(String name, Integer age) {

       super();

       this.name = name;

       this.age = age;

    }

    public User() {

       super();

       // TODO Auto-generated constructor stub

    }

    /**

     * @return the name

     */

    public String getName() {

       return name;

    }

    /**

     * @param name the name to set

     */

    public void setName(String name) {

       this.name = name;

    }

    /**

     * @return the age

     */

    public Integer getAge() {

       return age;

    }

    /**

     * @param age the age to set

     */

    public void setAge(Integer age) {

       this.age = age;

    }

    /* (non-Javadoc)

     * @see java.lang.Object#toString()

     */

    @Override

    public String toString() {

       return "User [name=" + name + ", age=" + age + "]";

    }

   

}

 

 

User1Mapper.java

package com.xiangshuai.user1mapper;

 

import java.util.List;

 

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Param;

import org.apache.ibatis.annotations.Select;

 

import com.xiangshuai.pojo.User;

 

public interface User1Mapper {

         @Select("SELECT * FROM USERS WHERE NAME = #{name}")

         User findByName(@Param("name") String name);

        

         @Select("SELECT * FROM USERS WHERE NAME like concat('%',#{name},'%')")

         List<User> findByNameLike(@Param("name") String name);

        

         @Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")

         int insert(@Param("name") String name, @Param("age") Integer age);

 

}

 

User2Mapper.java

package com.xiangshuai.user2mapper;

 

 

import java.util.List;

 

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Param;

import org.apache.ibatis.annotations.Select;

 

import com.xiangshuai.pojo.User;

 

public interface User2Mapper {

         @Select("SELECT * FROM USERS WHERE NAME = #{name}")

         User findByName(@Param("name") String name);

        

         @Select("SELECT * FROM USERS WHERE NAME like concat('%',#{name},'%')")

         List<User> findByNameLike(@Param("name") String name);

        

         @Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")

         int insert(@Param("name") String name, @Param("age") Integer age);

 

}

 

 

User3Mapper.java

package com.xiangshuai.user3mapper;

 

 

import java.util.List;

 

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Param;

import org.apache.ibatis.annotations.Select;

 

import com.xiangshuai.pojo.User;

 

public interface User3Mapper {

         @Select("SELECT * FROM USER WHERE NAME = #{name}")

         User findByName(@Param("name") String name);

        

         @Select("SELECT * FROM USER WHERE NAME like concat('%',#{name},'%')")

         List<User> findByNameLike(@Param("name") String name);

        

         @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")

         int insert(@Param("name") String name, @Param("age") Integer age);

 

}

 

application.properties

spring.datasource.test1.driver-class-name= com.mysql.jdbc.Driver

spring.datasource.test1.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8

spring.datasource.test1.username =root

spring.datasource.test1.password =ma

 

spring.datasource.test2.driver-class-name= com.mysql.jdbc.Driver

spring.datasource.test2.url = jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8

spring.datasource.test2.username =root

spring.datasource.test2.password =ma

 

 

 

spring.datasource.test3.driver-class-name= com.mysql.jdbc.Driver

spring.datasource.test3.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8

spring.datasource.test3.username =root

spring.datasource.test3.password =ma

 

 

个数据库表在(后面补上的)

 

 

 

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值