SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟
1、項(xiàng)目構(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 進(jìn)行 mongo 的相關(guān)操作,寫一個(gè)基礎(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 { /*// 無認(rèn)證的初始化方法 return new SimpleMongoDbFactory(new MongoClient(host, port), database);*/ //有認(rèn)證的初始化方法 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 抽象類,有多少個(gè)數(shù)據(jù)源就需要新建多少個(gè)數(shù)據(jù)源加載類
3.1、第一個(gè)數(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、第二個(gè)數(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、多個(gè)數(shù)據(jù)源中有一個(gè) bean 需要設(shè)置為 mongoTemplate ,且必須添加 @Primary 注解,否則 WebMvcConfigurationSupport.class 等會(huì)報(bào)錯(cuò)找不到 mongoTemplate
2、Spring Boot 會(huì)自動(dòng)注入 mongoTemplate ,與我們配置的多個(gè)數(shù)據(jù)源有沖突。為了防止默認(rèn)注入,需要排除自動(dòng)注入的類。在 Spring Boot 的啟動(dòng)類 Applocation.java 添加排除類注解
@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
5、使用多個(gè)數(shù)據(jù)源
使用時(shí),直接對(duì)應(yīng)注入即可
@Autowired @Qualifier(value = "mongoTemplate") MongoTemplate mongoTemplate; @Autowired @Qualifier(value = "authMongoTemplate") MongoTemplate authMongoTemplate;
6、可能遇到的問題
1、'com.mongodb.MongoClient' that could not be found
詳細(xì)報(bào)錯(cuò)如下:
***************************
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)致原來的自動(dòng)注入缺少 bean
解決方式:主要是看哪個(gè)自動(dòng)注入的類在引用默認(rèn)的 MongoClient ,把它排除出去即可,例如:
@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
2、more than one ‘primary' bean found among candidates
詳細(xì)報(bào)錯(cuò)如下:
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 會(huì)自動(dòng)注入一個(gè)默認(rèn)的 mongoTemplate 或者設(shè)置了多個(gè) @Primary 數(shù)據(jù)源
解決方式:排除 Spring Boot 自動(dòng)注入的類,自動(dòng)重寫的 mongoTemplate 需要且只能設(shè)置一個(gè)為@Primary
到此這篇關(guān)于SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟的文章就介紹到這了,更多相關(guān)SpringBoot MongoDB多數(shù)據(jù)源內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Java中Comparable和Comparator接口的區(qū)別
這篇文章主要介紹了詳解Java中Comparable和Comparator接口的區(qū)別的相關(guān)資料,希望通過本文大家能徹底掌握這部分內(nèi)容,需要的朋友可以參考下2017-09-09關(guān)于Spring事務(wù)隔離、傳播屬性與@Transactional注解
這篇文章主要介紹了關(guān)于事務(wù)隔離、Spring傳播屬性與@Transactional注解,如果一組處理步驟或者全部發(fā)生或者一步也不執(zhí)行,我們稱該組處理步驟為一個(gè)事務(wù),需要的朋友可以參考下2023-05-05Java實(shí)戰(zhàn)之酒店人事管理系統(tǒng)的實(shí)現(xiàn)
這篇文章主要介紹了如何用Java實(shí)現(xiàn)酒店人事管理系統(tǒng),文中采用的技術(shù)有:JSP、Spring、SpringMVC、MyBatis等,感興趣的小伙伴可以學(xué)習(xí)一下2022-03-03Spring?Security配置多個(gè)數(shù)據(jù)源并添加登錄驗(yàn)證碼的實(shí)例代碼
這篇文章主要介紹了Spring?Security配置多個(gè)數(shù)據(jù)源并添加登錄驗(yàn)證碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08MybatisPlus使用@TableLogic實(shí)現(xiàn)邏輯刪除過程
這篇文章主要介紹了MybatisPlus使用@TableLogic實(shí)現(xiàn)邏輯刪除過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05Mybatis結(jié)果集映射與生命周期詳細(xì)介紹
結(jié)果集映射指的是將數(shù)據(jù)表中的字段與實(shí)體類中的屬性關(guān)聯(lián)起來,這樣 MyBatis 就可以根據(jù)查詢到的數(shù)據(jù)來填充實(shí)體對(duì)象的屬性,幫助我們完成賦值操作2022-10-10詳解java 中Spring jsonp 跨域請(qǐng)求的實(shí)例
這篇文章主要介紹了詳解java 中Spring jsonp 跨域請(qǐng)求的實(shí)例的相關(guān)資料,jsonp 可用于解決主流瀏覽器的跨域數(shù)據(jù)訪問的問題,需要的朋友可以參考下2017-08-08