Springboot之集成MongoDB无认证与开启认证的配置方式
文章目录
- Springboot之集成MongoDB无认证与开启认证的配置方式
- [1. application.yml中两种配置方式](#1. application.yml中两种配置方式)
-
- [1. 无认证集成yaml配置](#1. 无认证集成yaml配置)
- [2. 有认证集成yaml配置](#2. 有认证集成yaml配置)
- [2. 测试](#2. 测试)
-
- [1. 实体类](#1. 实体类)
- [2. 单元测试](#2. 单元测试)
- [3. 编写Controller测试](#3. 编写Controller测试)
1. application.yml中两种配置方式
1. 无认证集成yaml配置
application.yml
配置如下
yaml
spring:
application:
name: yuan-boot-mongo
data:
mongodb:
uri: mongodb://127.0.0.1:27017/wei
2. 有认证集成yaml配置
application.yml
配置如下
yaml
spring:
application:
name: yuan-boot-mongo
data:
mongodb:
authentication-database: admin
database: wei
username: admin
password: admin123
host: 127.0.0.1
port: 27017
2. 测试
1. 实体类
User.java
如下
java
package com.yuan.lab.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String id;
private String name;
private Integer age;
private Date day;
}
2. 单元测试
YuanLimsBootApplicationTests.java
如下
java
package com.yuan;
import com.yuan.lab.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.Date;
@SpringBootTest
class YuanLimsBootApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
void contextLoads() {
User user = new User("num1","jinshengyuan",22,new Date());
User user1 = mongoTemplate.insert(user,"mytest");
System.out.println(user1);
}
}
3. 编写Controller测试
MongoController.java
如下
java
package com.yuan.lab.controller;
import com.yuan.lab.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping("/mongo")
public class MongoController {
@Autowired
private MongoTemplate mongoTemplate;
public Object mongoTest(){
User user = new User("num1","jinshengyuan",22,new Date());
User user1 = mongoTemplate.insert(user,"mytest");
return user1;
}
}