Springboot之集成MongoDB无认证与开启认证的配置方式
文章目录
1. application.yml中两种配置方式
1. 无认证集成yaml配置
application.yml
配置如下
spring:application:name: yuan-boot-mongo
data:mongodb:uri: mongodb://127.0.0.1:27017/wei
2. 有认证集成yaml配置
application.yml
配置如下
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
如下
packagecom.yuan.lab.entity;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importjava.util.Date;@Data@NoArgsConstructor@AllArgsConstructorpublicclassUser{privateString id;privateString name;privateInteger age;privateDate day;}
2. 单元测试
YuanLimsBootApplicationTests.java
如下
packagecom.yuan;importcom.yuan.lab.entity.User;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.mongodb.core.MongoTemplate;importjava.util.Date;@SpringBootTestclassYuanLimsBootApplicationTests{@AutowiredprivateMongoTemplate mongoTemplate;@TestvoidcontextLoads(){User user =newUser("num1","jinshengyuan",22,newDate());User user1 = mongoTemplate.insert(user,"mytest");System.out.println(user1);}}
3. 编写Controller测试
MongoController.java
如下
packagecom.yuan.lab.controller;importcom.yuan.lab.entity.User;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.repository.Query;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.Date;@RestController@RequestMapping("/mongo")publicclassMongoController{@AutowiredprivateMongoTemplate mongoTemplate;publicObjectmongoTest(){User user =newUser("num1","jinshengyuan",22,newDate());User user1 = mongoTemplate.insert(user,"mytest");return user1;}}
本文转载自: https://blog.csdn.net/yuanjinshenglife/article/details/136290657
版权归原作者 小袁搬码 所有, 如有侵权,请联系我们删除。
版权归原作者 小袁搬码 所有, 如有侵权,请联系我们删除。