java - 这是与我的文件(application.properties)中的 mongodb 配置有关的问题吗?
问题描述
致我的开发者伙伴们,
模棱两可的错误日志没有明确指出哪些文件出错了,这可能是一些最麻烦的错误。我是一个玩 java spring 的新手。下面是我尝试运行公共类 SpringWithMongodbApplication 时遇到的错误。
我已确保 application.properties 中的凭据正确。顺便说一句,查找类似的错误,我发现终端内的错误日志与其他帖子不同。PLS 帮助 <3
终端内部错误:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootTutorialApplication': Unsatisfied dependency expressed through field 'groceryItemRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemRepository' defined in com.example.springboottutorial.repository.ItemRepository defined in @EnableMongoRepositories declared on SpringBootTutorialApplication: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Unsatisfied dependency expressed through method 'mongoDatabaseFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is com.mongodb.MongoConfigurationException: Unable to look up TXT record for host cluster0.mongodb.net
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.10.jar:5.3.10]
SpringWithMongodbApplication 内的代码:
package com.example.springboottutorial;
import com.example.springboottutorial.model.GroceryItem;
import com.example.springboottutorial.repository.CustomItemRepository;
import com.example.springboottutorial.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.List;
@SpringBootApplication
@EnableMongoRepositories
public class SpringBootTutorialApplication implements CommandLineRunner {
@Autowired
ItemRepository groceryItemRepo;
@Autowired
CustomItemRepository customRepo;
public static void main(String[] args) {
SpringApplication.run(SpringBootTutorialApplication.class, args);
}
@Override
public void run(String... args) {
System.out.println("--------------CREATE GROCERY ITEMS------------------");
createGroceryItems();
System.out.println("\n----------------SHOW ALL GROCERY ITEMS---------------------------\n");
showAllGroceryItems();
System.out.println("\n--------------GET ITEM BY NAME-----------------------------------\n");
getGroceryItemByName("Whole Wheat Biscuit");
System.out.println("\n-----------GET ITEMS BY CATEGORY---------------------------------\n");
getItemsByCategory("millets");
System.out.println("\n-----------UPDATE CATEGORY NAME OF SNACKS CATEGORY----------------\n");
updateCategoryName("snacks");
System.out.println("\n----------DELETE A GROCERY ITEM----------------------------------\n");
deleteGroceryItem("Kodo Millet");
System.out.println("\n------------FINAL COUNT OF GROCERY ITEMS-------------------------\n");
findCountOfGroceryItems();
System.out.println("\n-------------------THANK YOU---------------------------");
System.out.println("\n-----------UPDATE QUANTITY OF A GROCERY ITEM------------------------\n");
updateItemQuantity("Bonny Cheese Crackers Plain", 10);
}
void createGroceryItems() {
System.out.println("Data creation started...");
groceryItemRepo.save(new GroceryItem("Whole Wheat Biscuit", "Whole Wheat Biscuit", 5, "snacks"));
groceryItemRepo.save(new GroceryItem("Kodo Millet", "XYZ Kodo Millet healthy", 2, "millets"));
groceryItemRepo.save(new GroceryItem("Dried Red Chilli", "Dried Whole Red Chilli", 2, "spices"));
groceryItemRepo.save(new GroceryItem("Pearl Millet", "Healthy Pearl Millet", 1, "millets"));
groceryItemRepo.save(new GroceryItem("Cheese Crackers", "Bonny Cheese Crackers Plain", 6, "snacks"));
groceryItemRepo.save(new GroceryItem("Chocolate Candies", "Maltesers", 3, "sweets"));
groceryItemRepo.save(new GroceryItem("Squid Slices", "Four Islands", 6, "snacks"));
System.out.println("Data creation complete...");
}
//show all data
public void showAllGroceryItems() {
groceryItemRepo.findAll().forEach(item -> System.out.println(getItemDetails(item)) );
}
// Get item by name
public void getGroceryItemByName(String name) {
System.out.println("getting item by name: " + name);
GroceryItem item = groceryItemRepo.findItemByName(name);
System.out.println(getItemDetails(item));
}
// get name and quantiy of all item of a particular category
public void getItemsByCategory(String category) {
System.out.println("Getting items for the category" + category);
List<GroceryItem> list = groceryItemRepo.findAll(category);
list.forEach(item -> System.out.println("Name: " + item.getName() + ", Quantity: " + item.getQuantity()));
}
public void findCountOfGroceryItems() {
long count = groceryItemRepo.count();
System.out.println("Number of documents in the collection: " + count);
}
public String getItemDetails(GroceryItem item) {
System.out.println(
"Item Name: " + item.getName() +
", \nQuantity: " + item.getQuantity() +
", \nItem Category: " + item.getCategory()
);
return "";
}
public void updateCategoryName(String category) {
//new value
String newCategory = "munchies";
// List all items with category snacks
List<GroceryItem> list = groceryItemRepo.findAll(category);
list.forEach(item -> {
//Update the category in each document
item.setCategory(newCategory);
});
//Save all the items in the databse
List<GroceryItem> itemsUpdated = groceryItemRepo.saveAll(list);
if(itemsUpdated != null)
System.out.println("Successfully updated " + itemsUpdated.size() + " items.");
}
//DELETE
public void deleteGroceryItem(String id) {
groceryItemRepo.deleteById(id);
System.out.println("Item with id " + id + " deleted...");
}
public void deleteAllGroceryItems() {
groceryItemRepo.deleteAll();
System.out.println("All items inside Grocery deleted");
}
//UPDATE
public void updateItemQuantity(String name, float newQuantity) {
System.out.println("Updating quantity for " + name);
customRepo.updateItemQuantity(name, newQuantity);
}
}
ItemRepository 内的代码:
package com.example.springboottutorial.repository;
import com.example.springboottutorial.model.GroceryItem;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
public interface ItemRepository extends MongoRepository<GroceryItem, String> {
@Query("{name: '?0'}")
GroceryItem findItemByName(String name);
@Query(value="{category:'?0'}", fields="{'name' : 1, 'quantity' : 1}")
List<GroceryItem> findAll (String category);
public long count();
}
CustomItemRepositoryImpl 内的代码:
package com.example.springboottutorial.repository;
import com.example.springboottutorial.model.GroceryItem;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
public class CustomItemRepositoryImpl implements CustomItemRepository{
@Autowired
MongoTemplate mongoTemplate;
public void updateItemQuantity(String name, float newQuantity) {
Query query = new Query(Criteria.where("name").is(name));
Update update = new Update();
update.set("quantity", newQuantity);
UpdateResult result = mongoTemplate.updateFirst(query, update, GroceryItem.class);
if(result == null)
System.out.println("No documents updated");
else
System.out.println(result.getModifiedCount() + " documents(s) updated..");
}
}
CustomItemRepository 内的代码:
package com.example.springboottutorial.repository;
public interface CustomItemRepository {
void updateItemQuantity(String name, float newQuantity);
}
GroceryItem 内的代码:
package com.example.springboottutorial.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document("groceryitems")
public class GroceryItem {
@Id
private String id;
private String name;
private int quantity;
private String category;
public GroceryItem(String id, String name, int quantity, String category) {
super();
this.id = id;
this.name = name;
this.quantity = quantity;
this.category = category;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public String getCategory() {
return category;
}
public void setCategory(String newCategory) {
this.category = newCategory;
}
// public void getName(String name) {
// this.name = name;
// }
}
代码里面 application.properties:
spring.data.mongodb.uri=mongodb+srv://reactmaster123:react8927@cluster0.mongodb.net/mygrocerylist
spring.data.mongodb.database=mygrocerylist
文件结构截图:[1]:https ://i.stack.imgur.com/zdDbe.png
解决方案
推荐阅读
- android - FirebaseRecyclerAdapter 如何从数据库实时获取数据?什么是使用 addValueEventListener 或 addListenerForSingleValueEvent...?
- python - 在创建动态子类型时摆脱“if”语句
- extendscript - 使用 selectedLayers 属性过滤文本图层
- python - 从 python 中的“请求”模块写入文件时添加不必要的字符
- playframework - 无法使用 sbt Tests.setup 运行播放应用程序进行集成测试
- java - JSP web应用程序数据库连接无法加载
- javascript - 居中滚动到元素到通过#?(不修改 DOM / 使用 refs)
- node.js - 使用redis列表时nodejs上的偶尔错误
- mysql - 这个差旅管理操作的 SQL 查询是什么?
- python - 访问没有标签的 html 元素