Spring之xml配置方式快速整合MongoDB
文章目录
- Spring之xml配置方式快速整合MongoDB
- [1. MongoDB](#1. MongoDB)
-
- [1. 引依赖](#1. 引依赖)
- [2. application.properties](#2. application.properties)
- [3. application-context-mongodb.xml](#3. application-context-mongodb.xml)
1. MongoDB
MongoDB 版本: 4.2.21
1. 引依赖
xml
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.7.2</version>
</dependency>
2. application.properties
properties
mongo.username=test
mongo.password=test
mongo.host=127.0.0.1
mongo.port=27017
mongo.dbname=test_doc
mongo.authenticationDbname=admin
mongo.authMechanism=SCRAM-SHA-1
3. application-context-mongodb.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 有认证的配置 -->
<mongo:db-factory id="mongoDbFactory" client-uri="mongodb://${mongo.username}:${mongo.password}@${mongo.host}:${mongo.port}/${mongo.dbname}?authSource=${mongo.authenticationDbname}&authMechanism=${mongo.authMechanism}"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<!-- 自动扫描 -->
<mongo:mapping-converter base-package="com.yuan.mongo.page.*" />
<context:annotation-config />
<!-- 自定义注解类 -->
<context:component-scan base-package="com.yuan.mongo,caom.yuan.utils" />
<bean class="org.springframework.data.mongodb.core.mapping.event.LoggingEventListener" />
</beans>