我是 Spring Boot 应用程序的初学者,最近我发现这个项目有以下 3 个包
com.packagename.controller
com.packagname.domain
com.packagename.service
在域包中,有一个名为Student的类 有以下代码
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [name=" + name + "]";
}
然后在服务包中, 类StudentService
package com.javTpoint.service;
import org.springframework.stereotype.Service;
import com.javTpoint.domain.Student;
@Service
public class StudentService {
public Student saveStudent(Student student) {
student.setName(student.getName() + "123");
return student;
}
}
最后在 Controller 包中, 学生类
package com.javTpoint.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javTpoint.domain.Student;
import com.javTpoint.service.StudentService;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/student", method = RequestMethod.POST)
Student saveStuden(@RequestBody Student student) {
System.out.println(student);
return studentService.saveStudent(student);
}
}
要求使用它的程序是Postman
我只是想了解工作流程是如何发生的
为什么在 Controller 的 saveStuden()
方法中使用 @RequestBody
。
最佳答案
使用 Postman 时,您可能会调用诸如 http://<host>:<port>/student
之类的 URL使用 HTTP POST
提交(可能)以 JSON 表示的有效负载的方法,例如
{ "name": "aName" }
Postman 的流程如下:
- postman
POST
s 请求正文。 - 公开
http://<host>:<port>/student
的应用程序使用请求,将请求正文反序列化为Student
对象并委托(delegate)给StudentController
的实例。这个:@RequestBody Student student
指示 Spring 将给定的有效负载反序列化为Student
的实例. StudentController
委托(delegate)给StudentService
的实例它已被注入(inject)。注:@Autowired
注解指示 Spring 的依赖注入(inject)机制创建StudentController
的实例实例为StudentService
注入(inject)其中。StudentService
将“123”附加到学生姓名并返回突变的Student
实例。StudentController
返回突变的Student
实例。- 框架(即 Spring Boot)序列化返回的
Student
并将序列化表示返回给 Postman。
您在OP中描述的内容看起来像是一个共同的职责分工:
- 框架(在本例中为 Spring Boot)提供 servlet 容器片段,并将 HTTP 调用映射到 Controller 类上的公共(public)方法
- Controller 提供 HTTP 端点集成,通常是服务上的轻量级外观
- 服务负责对给定对象“执行某些操作”
更新以回应此评论:
where should I learn what you know from? Any personal recommendations?
您可以从 this Spring Boot example 开始并逐步完成它。一旦你让它工作(通常不超过 15 分钟),然后使用...
- 记录
- 调试
- 改变事物(一次一件事)并观察因果关系
...帮助您了解 Spring 在“幕后”所做的事情。
关于java - 这个Spring Boot程序的工作流程是怎样的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47634149/