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 ***.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 ***.yuan;

import ***.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 ***.yuan.lab.controller;

import ***.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;
    }
}

转载请说明出处内容投诉
CSS教程_站长资源网 » Springboot之集成MongoDB无认证与开启认证的配置方式

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买