我在 Spring Boot 中创建了一个带有 getter 和 setter 以及参数化构造函数的 bean,它由我的控制器类访问。但是一旦我删除了 getter 和 setter,控制器类就无法再访问该变量了。
我无法理解我的构造函数如何使用 getter setter,即使我从未调用过它们。
// THIS IS THE BEAN CLASS
package net.javaguides.api.bean;
public class Student {
private int id;
private String firstName;
private String lastName;
public Student(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
//we use this keyword to avoid confusion between local variable and instance variable
//this is used for instance variable
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
// THIS IS THE CONTROLLER CLASS
package net.javaguides.api.controller;
import net.javaguides.api.bean.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
//for boilerplate code use @RestController
@RestController
public class StudentController {
//make a method that returns the properties of the student bean/class/entity
//it needs to return the object properties so, the return type will be an object type
//make the method a http get method by using @
@GetMapping("/studentdetails")
public Student studentapi(){
Student st = new Student(
1,
"Gurjas",
"Sahney"
);
return st;
}
}
当我删除 getter 和 setter 时,它不起作用,如果我删除 getter setter,就会发生这种情况(img 已发布) 谁在这里调用 getter 和 setter?
您在
Student
方法中返回 RestController
并以 json
格式获得响应 spring-boot-starter-web
使用 Jackson API 将对象转换为 JSON
并且 Jackson API 需要 Getter 和 Setter 方法来序列化Student
对象正确转换为 JSON。