java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot MongoDB无认证与认证配置

Springboot集成MongoDB无认证与开启认证的配置方式

作者: 小袁搬码

本文主要介绍了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如下

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如下

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如下

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;
    }
}

到此这篇关于Springboot集成MongoDB无认证与开启认证的配置方式的文章就介绍到这了,更多相关Springboot MongoDB无认证与认证配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文