SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟
1、項目構(gòu)建
添加 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、配置相應(yīng)的數(shù)據(jù)源
采用 mongoTemplate 進行 mongo 的相關(guān)操作,寫一個基礎(chǔ)的抽象類
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;
}
數(shù)據(jù)源加載需要繼承 AbstractMongoConfigure 抽象類,有多少個數(shù)據(jù)源就需要新建多少個數(shù)據(jù)源加載類
3.1、第一個數(shù)據(jù)源
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 的值用于相應(yīng)的基礎(chǔ)包,prefix 為 application.properties 中的配置值
3.2、第二個數(shù)據(jù)源
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、多個數(shù)據(jù)源中有一個 bean 需要設(shè)置為 mongoTemplate ,且必須添加 @Primary 注解,否則 WebMvcConfigurationSupport.class 等會報錯找不到 mongoTemplate
2、Spring Boot 會自動注入 mongoTemplate ,與我們配置的多個數(shù)據(jù)源有沖突。為了防止默認注入,需要排除自動注入的類。在 Spring Boot 的啟動類 Applocation.java 添加排除類注解
@SpringBootApplication(exclude = {
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class})
5、使用多個數(shù)據(jù)源
使用時,直接對應(yīng)注入即可
@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 等之后導(dǎo)致原來的自動注入缺少 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 或者設(shè)置了多個 @Primary 數(shù)據(jù)源
解決方式:排除 Spring Boot 自動注入的類,自動重寫的 mongoTemplate 需要且只能設(shè)置一個為@Primary
到此這篇關(guān)于SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟的文章就介紹到這了,更多相關(guān)SpringBoot MongoDB多數(shù)據(jù)源內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot如何解析應(yīng)用參數(shù)args
文章主要介紹了SpringBoot啟動過程中如何解析`main`函數(shù)中的參數(shù)`args`,包括如何解析命令行參數(shù)、訪問選項參數(shù)和非選項參數(shù),接著,介紹了`ApplicationArguments`接口及其方法,感興趣的朋友跟隨小編一起看看吧2024-11-11
Spring中@Transactional注解關(guān)鍵屬性和用法小結(jié)
在Spring框架中,@Transactional 是一個注解,用于聲明事務(wù)性的方法,它提供了一種聲明式的事務(wù)管理方式,避免了在代碼中直接編寫事務(wù)管理相關(guān)的代碼,本文給大家介紹@Transactional 注解的一些關(guān)鍵屬性和用法,感興趣的朋友一起看看吧2023-12-12
SpringBoot中MyBatis-Plus 查詢時排除某些字段的操作方法
這篇文章主要介紹了SpringBoot中MyBatis-Plus 查詢時排除某些字段的操作方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
SpringBoot整合jasypt實現(xiàn)敏感信息的加密詳解
一般公司的核心業(yè)務(wù)代碼中,都會存在與數(shù)據(jù)庫、第三方通信的secret key等敏感信息,如果以明文的方式存儲,一旦泄露,那將會給公司帶來巨大的損失。本篇文章通過講解:Springboot集成Jasypt對項目敏感信息進行加密,提高系統(tǒng)的安全性2022-09-09
解決Servlet4.0版本使用注解設(shè)置url但無法訪問的問題
在學(xué)習(xí)servlet過程中,使用web.xml文件配置servlet可以正常訪問,但使用WebServlet注解時出現(xiàn)404錯誤,解決方法是在web.xml文件中將metadata-complete屬性改為false,啟動標注支持,然而該方法對我無效,最后通過重建項目和手動將新建的項目添加到tomcat服務(wù)器解決問題2024-10-10
MyBatis-Plus多數(shù)據(jù)源的示例代碼
本文主要介紹了MyBatis-Plus多數(shù)據(jù)源的示例代碼,包括依賴配置、數(shù)據(jù)源配置、Mapper 和 Service 的定義,具有一定的參考價值,感興趣的可以了解一下2024-05-05

