栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

通过Spring Boot应用访问mongodb时出现身份验证错误

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过Spring Boot应用访问mongodb时出现身份验证错误

我发现了问题。为了确保该线程的完整性,我将分享答案,包括代码。问题是我错误地使用了应用程序属性spring.data.mongodb.uri:它在URI中没有用户名和密码,因为我错误地认为spring.data.mongodb.username和spring.data.mongodb.password涵盖了。因此,要么将uri与用户名和密码一起使用,要么显式使用主机和数据库(也许还有端口)spring属性。这是代码。它将在支持mongoDB的spring
boot应用程序中运行(使用initializr或IntelliJ创建该项目)。我有一个模型:

package net.IndyStef.model;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.document;@document(collection = "person")public class Person {@Idprivate String id;private String name;private Integer age;public Person() {}public Person(String id) {    this.id = id;}public Person(String id, String name, Integer age) {    this.id = id;    this.name = name;    this.age = age;}... getters/setters omitted for breverity ...}

通过存储库读取和写入数据:

package net.IndyStef.repository;import net.okrongli.model.Person;import org.springframework.data.mongodb.repository.MongoRepository;public interface PersonRepository extends MongoRepository<Person, String> {}

数据库名称,主机和凭据位于application.properties文件中:

spring.data.mongodb.host=192.168.1.90spring.data.mongodb.database=peoplespring.data.mongodb.username=userspring.data.mongodb.password=password#spring.data.mongodb.uri=mongodb://192.168.1.90/people

重要的是不要将uri与数据库和用户名混合使用。如果使用uri,则需要包含用户名和密码,如下所示:

spring.data.mongodb.uri=mongodb://user:password@192.168.1.90/people

为了测试这一点,我使用了一个简单的Spring命令行运行程序:

package net.IndyStef;import net.IndyStef.model.Person;import net.IndyStef.repository.PersonRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import java.util.List;@SpringBootApplicationpublic class MongoDbTestApplication implements CommandLineRunner {    public static void main(String[] args) {        SpringApplication.run(MongoDbTestApplication.class, args);    }    @Autowired    private PersonRepository repository;    @Override    public void run(String... args) {        repository.save(new Person("peter.pan", "Peter Pan", 865));        List<Person> people = repository.findAll();        for (Person person: people) { System.out.println(person);        }    }}

我希望这种解释能帮助无法理解的其他人,例如我几天。

谢谢,

斯特凡



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/374592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号