包阅导读总结
1. `Full-stack`、`Java`、`Spring Boot`、`TodoService`、`CRUD 操作`
2. 这段文本主要介绍了使用 Java、Spring Boot 等技术构建的 `TodoService` 类,阐述了其注解和自动装配 `TodoRepository` 的方式,以及该类中进行的 CRUD 操作。
3.
– `TodoService` 类被注解为 `@Service`,以表明其为服务类,使描述更清晰。
– 虽不是严格要求,但可提高可读性。
– 通过 `@Autowired` 引入 `TodoRepository` 类,由 Spring 按类型填充。
– 默认使用单例注入,适用于当前场景。
– 该类包含多个方法进行 CRUD 操作。
– `getTodos` 方法获取所有待办事项。
– `createTodo` 方法创建待办事项。
– `getTodo` 方法根据 ID 获取待办事项。
– `deleteTodo` 方法根据 ID 删除待办事项。
– `saveTodo` 方法保存待办事项。
思维导图:
文章来源:infoworld.com
作者:InfoWorld
发布时间:2024/7/31 9:00
语言:英文
总字数:1465字
预计阅读时间:6分钟
评分:88分
标签:全栈开发,Java,React,Spring Boot,MongoDB
以下为原文内容
本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com
// src/main/java/com/example/iwreactspring/service/TodoService.java package com.example.iwreactspring.service;import java.util.List;import java.util.ArrayList;import com.example.iwreactspring.model.TodoItem;import org.springframework.stereotype.Service;import org.springframework.beans.factory.annotation.Autowired;import com.mongodb.client.MongoClient;import com.mongodb.client.MongoClients;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;import org.bson.codecs.configuration.CodecRegistry;import org.bson.codecs.pojo.PojoCodecProvider;import org.bson.Document;import com.example.iwreactspring.repository.TodoRepository;@Servicepublic class TodoService { @Autowired private TodoRepository todoRepository; public List<TodoItem> getTodos() { return todoRepository.findAll(); } public TodoItem createTodo(TodoItem newTodo) { TodoItem savedTodo = todoRepository.save(newTodo); return savedTodo; } public TodoItem getTodo(String id) { return todoRepository.findById(id).orElse(null); } public boolean deleteTodo(String id) { TodoItem todoToDelete = getTodo(id); if (todoToDelete != null) { todoRepository.deleteById(id); return true; } else { return false; } } public TodoItem saveTodo(TodoItem todoItem) { TodoItem savedTodo = todoRepository.save(todoItem); return savedTodo; }}
We annotate this class with @Service
to denote it as a service class. Again, this is not strictly required, because Spring can use the class as an injected bean without the annotation, but annotating the class makes things more descriptive. Next, we use @AutoWired
to bring the TodoRepository
class in. This will be populated by Spring based on the class type, which is the com.example.iwreactspring.repository.TodoRepository
we saw earlier.
By default, Spring uses singleton injection (one instance of the injected bean class), which works well for us.
CRUD operations on the service class
Each method on this class is dedicated to performing one CRUD operation using the repository. For example, we need a way to get all the to-dos in the database, and getTodos()
does that for us. The Repository
class makes it very easy, too: return todoRepository.findAll()
returns all the records (aka documents) in the todo collection (aka, database).