这篇基础原理很详细了,https://zhuanlan.zhihu.com/p/32779910
但当需要继承父类时会有些问题,主要涉及到问题是
1.tostring输出时默认不会输出父类属性 需要加上@ToString(callSuper = true)
2.equals比较时默认也不会比较父类属性,需要加上@EqualsAndHashCode(callSuper = true)
3.builder子类不会默认支持父类的属性,需要在子类和父类都加上@SuperBuilder
//Person.java
package com.example.helloworld.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;
/*
*1.安装lombok插件
*2.pom中引入lombok依赖
*3.annotation process 勾上enable annotation processing
*/
@Data
@NoArgsConstructor
@AllArgsConstructor(access=AccessLevel.PACKAGE)
@SuperBuilder
public class Person {
private String name;
private int age;
private int sex;
}
//Student.java
package com.example.helloworld.models;
import lombok.*;
@Data
/*默认 继承类的tostring是不会管父类成员的,加上这个注解可以输出父类成员信息*/
@ToString(callSuper = true)
/*默认状态时父类属性不同,子类属性不同,equals属性会为true*/
@EqualsAndHashCode(callSuper = true)
public class Student extends Person{
private String studentNo;
}
//Teacher.java
package com.example.helloworld.models;
import lombok.*;
import lombok.experimental.SuperBuilder;
@Data
@ToString(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class Teacher extends Person{
private String teacherNo;
}
//TestController
package com.example.helloworld.controller;
//import com.example.helloworld.models.Car;
import com.example.helloworld.models.Person;
import com.example.helloworld.models.Student;
import com.example.helloworld.models.Teacher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
/* @RequestMapping("/test")
public String Test() {
Car car = new Car();
car.setPlateNumber("粤A93023");
return car.getPlateNumber();
}
*/
@RequestMapping("/test01")
public String Test01(){
Person person=new Person();
person.setName("xiaoer01");
return person.toString();
}
@RequestMapping("/test02")
public String Test02(){
Student student=new Student();
student.setName("xiaoer02");
student.setStudentNo("20210620");
return student.toString();
}
@RequestMapping("/test03")
public String Test03(){
Teacher teacher=new Teacher();
teacher.setName("xiaoer03");
teacher.setTeacherNo("TC20210625");
return teacher.toString();
}
@RequestMapping("/test04")
public String Test04(){
Teacher teacher=Teacher.builder().teacherNo("TC20210626").name("xiaoer04").build();
return teacher.toString();
}
}