这个Spring Boot程序的工作流程是什么

时间:2017-12-04 13:08:59

标签: java maven spring-boot

我是春季启动应用程序的初学者,我最近遇到了这个项目有以下3个包

  

com.packagename.controller

     

com.packagname.domain

     

com.packagename.service

域包中,有一个名为学生的类 拥有以下代码

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 + "]";
}

然后在服务包中,   class 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 我只是想了解工作流程是如何发生的 为什么@RequestBody在控制器中的saveStuden()方法中使用。

2 个答案:

答案 0 :(得分:1)

使用Postman时,您可能会使用HTTP http://<host>:<port>/student方法调用POST等URL来提交以JSON表示的有效负载(可能),例如。

{ "name": "aName" }

Postman的流程如下:

  1. 邮递员POST是请求正文。
  2. 公开http://<host>:<port>/student的应用程序使用请求,将请求主体反序列化为Student对象并委托给StudentController的实例。这个:@RequestBody Student student指示Spring将给定的有效负载反序列化为Student的实例。
  3. StudentController委托给它注入的StudentService实例。注意:@Autowired注释指示Spring的依赖注入机制创建StudentController的实例,注入实例StudentService
  4. StudentService将“123”附加到学生姓名并返回变异的Student个实例。
  5. StudentController返回变异的Student实例。
  6. 框架(即Spring Boot)序列化返回的Student并将序列化表示返回给Postman。
  7. 您在OP中描述的内容看起来像是一个共同的职责分工:

    • 框架(在本例中为Spring Boot)提供servlet容器部分并将HTTP调用映射到控制器类上的公共方法
    • 控制器提供HTTP端点集成,通常是服务的轻量级外观
    • 服务负责与给定对象“做某事”

    更新以回复此评论:

      

    我应该从哪里学到你的知识?任何个人建议?

    您可以从this Spring Boot example开始,一步一步地完成它。一旦你工作(通常不超过15分钟),然后使用......

    • 记录
    • 调试
    • 改变事物(一次一件事)并观察因果关系

    ...帮助您了解Spring正在做什么'在幕后'。

答案 1 :(得分:1)

@RequestBody参数之前的student注释意味着student对象将处理您将通过/student请求发送给POST uri的数据。< / p>

数据应以JSON格式发送:

例如:

{
    name: "Joe Doe"
}

studentService.saveStudent(student)将改变student对象的数据,输出将是。

{
    name: "Joe Doe123"
}
相关问题