SpringBoot配置MongoDB多数据源的方法步骤

 更新时间:2020年10月27日 14:26:59   作者:Xue8Tzxs  
这篇文章主要介绍了SpringBoot配置MongoDB多数据源的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1、项目构建

添加 pom 文件

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2、在 application.properties 中添加配置

##start mongodb for basic
#----------------------------------------------
basic.spring.data.mongodb.host=localhost
basic.spring.data.mongodb.port=27016
basic.spring.data.mongodb.username=auto_compute
basic.spring.data.mongodb.password=vqOqSZRs
basic.spring.data.mongodb.database=auto_compute
#----------------------------------------------
##end mongodb for spirit
##start mongodb for auth
#----------------------------------------------
auth.spring.data.mongodb.host=localhost
auth.spring.data.mongodb.port=27016
auth.spring.data.mongodb.username=datacenter
auth.spring.data.mongodb.password=Bds6NadsfafGlV
auth.spring.data.mongodb.database=datacenter
#----------------------------------------------
##end mongodb for spirit

3、配置相应的数据源

采用 mongoTemplate 进行 mongo 的相关操作,写一个基础的抽象类

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
public abstract class AbstractMongoConfigure {

  private String host;
  private int port;
  private String username;
  private String password;
  private String database;


  public MongoDbFactory mongoDbFactory() throws Exception {
    /*// 无认证的初始化方法
    return new SimpleMongoDbFactory(new MongoClient(host, port), database);*/

    //有认证的初始化方法
    ServerAddress serverAddress = new ServerAddress(host, port);
    List<MongoCredential> mongoCredentialList = new ArrayList<>();
    MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());
    mongoCredentialList.add(mongoCredential);
    return new SimpleMongoDbFactory(new MongoClient(serverAddress, mongoCredentialList), database);
  }

  abstract public MongoTemplate getMongoTemplate() throws Exception;
}

数据源加载需要继承 AbstractMongoConfigure 抽象类,有多少个数据源就需要新建多少个数据源加载类

3.1、第一个数据源

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.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.tcl.dc.autodata.dao.base"}, mongoTemplateRef = "mongoTemplate")
@ConfigurationProperties(prefix = "basic.spring.data.mongodb")
public class BasicMongoConfig extends AbstractMongoConfigure {

  @Primary
  @Bean(name = "mongoTemplate")
  @Override
  public MongoTemplate getMongoTemplate() throws Exception {
    return new MongoTemplate(mongoDbFactory());
  }
}

其中 basePackages 的值用于相应的基础包,prefix 为 application.properties 中的配置值

3.2、第二个数据源

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.tcl.dc.autodata.dao.auth"}, mongoTemplateRef = "authMongoTemplate")
@ConfigurationProperties(prefix = "auth.spring.data.mongodb")
public class AuthMongoConfig extends AbstractMongoConfigure {

  @Bean(name = "authMongoTemplate")
  @Override
  public MongoTemplate getMongoTemplate() throws Exception {
    return new MongoTemplate(mongoDbFactory());
  }
}

4、注意

1、多个数据源中有一个 bean 需要设置为 mongoTemplate ,且必须添加 @Primary 注解,否则 WebMvcConfigurationSupport.class 等会报错找不到 mongoTemplate

2、Spring Boot 会自动注入 mongoTemplate ,与我们配置的多个数据源有冲突。为了防止默认注入,需要排除自动注入的类。在 Spring Boot 的启动类 Applocation.java 添加排除类注解

@SpringBootApplication(exclude = {
    MongoAutoConfiguration.class,
    MongoDataAutoConfiguration.class})


5、使用多个数据源

使用时,直接对应注入即可

@Autowired
@Qualifier(value = "mongoTemplate")
MongoTemplate mongoTemplate;

@Autowired
@Qualifier(value = "authMongoTemplate")
MongoTemplate authMongoTemplate;

6、可能遇到的问题

1、'com.mongodb.MongoClient' that could not be found

详细报错如下:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method mongoDbFactory in org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration required a bean of type 'com.mongodb.MongoClient' that could not be found.
    - Bean method 'mongo' not loaded because auto-configuration 'MongoAutoConfiguration' was excluded


Action:

Consider revisiting the conditions above or defining a bean of type 'com.mongodb.MongoClient' in your configuration.

原因:重写了 MongoClient 等之后导致原来的自动注入缺少 bean

解决方式:主要是看哪个自动注入的类在引用默认的 MongoClient ,把它排除出去即可,例如:

@SpringBootApplication(exclude = {
    MongoAutoConfiguration.class,
    MongoDataAutoConfiguration.class})

2、more than one ‘primary' bean found among candidates

详细报错如下:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sampleController': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.MongoTemplate' available: more than one 'primary' bean found among candidates: [logMongoTemplate, userMongoTemplate, mongoTemplate]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at com.biologic.Applocation.main(Applocation.java:18) [classes/:na]
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.MongoTemplate' available: more than one 'primary' bean found among candidates: [logMongoTemplate, userMongoTemplate, mongoTemplate]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.determinePrimaryCandidate(DefaultListableBeanFactory.java:1365) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.determineAutowireCandidate(DefaultListableBeanFactory.java:1326) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1113) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

原因:Spring Boot 会自动注入一个默认的 mongoTemplate 或者设置了多个 @Primary 数据源

解决方式:排除 Spring Boot 自动注入的类,自动重写的 mongoTemplate 需要且只能设置一个为@Primary

到此这篇关于SpringBoot配置MongoDB多数据源的方法步骤的文章就介绍到这了,更多相关SpringBoot MongoDB多数据源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot如何解析应用参数args

    SpringBoot如何解析应用参数args

    文章主要介绍了SpringBoot启动过程中如何解析`main`函数中的参数`args`,包括如何解析命令行参数、访问选项参数和非选项参数,接着,介绍了`ApplicationArguments`接口及其方法,感兴趣的朋友跟随小编一起看看吧
    2024-11-11
  • Spring中@Transactional注解关键属性和用法小结

    Spring中@Transactional注解关键属性和用法小结

    在Spring框架中,@Transactional 是一个注解,用于声明事务性的方法,它提供了一种声明式的事务管理方式,避免了在代码中直接编写事务管理相关的代码,本文给大家介绍@Transactional 注解的一些关键属性和用法,感兴趣的朋友一起看看吧
    2023-12-12
  • springboot如何使用sm2加密传输

    springboot如何使用sm2加密传输

    这篇文章主要介绍了springboot如何使用sm2加密传输问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • SpringBoot中MyBatis-Plus 查询时排除某些字段的操作方法

    SpringBoot中MyBatis-Plus 查询时排除某些字段的操作方法

    这篇文章主要介绍了SpringBoot中MyBatis-Plus 查询时排除某些字段的操作方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08
  • SpringBoot整合jasypt实现敏感信息的加密详解

    SpringBoot整合jasypt实现敏感信息的加密详解

    一般公司的核心业务代码中,都会存在与数据库、第三方通信的secret key等敏感信息,如果以明文的方式存储,一旦泄露,那将会给公司带来巨大的损失。本篇文章通过讲解:Springboot集成Jasypt对项目敏感信息进行加密,提高系统的安全性
    2022-09-09
  • java实现雪花算法ID生成器工具类

    java实现雪花算法ID生成器工具类

    本文主要介绍了java实现雪花算法ID生成器工具类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • checkpoint 机制具体实现示例详解

    checkpoint 机制具体实现示例详解

    这篇文章主要为大家介绍了checkpoint 机制具体实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • 解决Servlet4.0版本使用注解设置url但无法访问的问题

    解决Servlet4.0版本使用注解设置url但无法访问的问题

    在学习servlet过程中,使用web.xml文件配置servlet可以正常访问,但使用WebServlet注解时出现404错误,解决方法是在web.xml文件中将metadata-complete属性改为false,启动标注支持,然而该方法对我无效,最后通过重建项目和手动将新建的项目添加到tomcat服务器解决问题
    2024-10-10
  • MyBatis-Plus多数据源的示例代码

    MyBatis-Plus多数据源的示例代码

    本文主要介绍了MyBatis-Plus多数据源的示例代码,包括依赖配置、数据源配置、Mapper 和 Service 的定义,具有一定的参考价值,感兴趣的可以了解一下
    2024-05-05
  • Java如何把文件夹打成压缩包并导出

    Java如何把文件夹打成压缩包并导出

    这篇文章主要介绍了Java如何把文件夹打成压缩包并导出,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01

最新评论