You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring框架毕业设计:用户注册模块Java Bean代码复用实现咨询

Implementing Class Inheritance for Reducing Redundancy in Spring Beans

Hey there! Great call on using inheritance to cut down on duplicate code in your graduation project—this is a clean, maintainable way to handle shared fields across related Java Beans. Let’s walk through the step-by-step implementation tailored for your Spring setup:

1. Create a Base Parent Class with Shared Fields

First, define a parent User class that holds all common fields (like name, email, etc.) that your other beans will reuse. Using Lombok’s @Data annotation automatically generates getters, setters, toString(), and other utility methods, saving you tons of boilerplate code:

import lombok.Data;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;

@Data
public class User {
    @NotBlank(message = "Name cannot be empty")
    private String name;
    
    @NotBlank(message = "Email cannot be empty")
    @Email(message = "Invalid email format")
    private String email;
    
    @NotBlank(message = "Password cannot be empty")
    private String password;
    
    // Add other shared fields here, e.g., createTime, lastLoginTime
}

2. Extend the Parent Class for Specific Beans

Now create your child classes (like Observer) that inherit from User and only define their unique fields. This way, you avoid repeating common fields while keeping each bean focused on its specific business attributes:

import lombok.Data;
import jakarta.validation.constraints.NotBlank;

@Data
public class Observer extends User {
    @NotBlank(message = "First name cannot be empty")
    private String firstname;
    
    @NotBlank(message = "Last name cannot be empty")
    private String lastname;
    
    // Add Observer-specific fields here, e.g., observerRole, organization
}

3. Use the Beans in Spring Controllers

In your Spring registration endpoints, you can directly use the child classes as request bodies. Spring’s message converters will automatically map both inherited and unique fields from incoming JSON requests:

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @PostMapping("/register/observer")
    public ResponseEntity<String> registerObserver(@Valid @RequestBody Observer observer) {
        // Your registration logic here: save to database, send confirmation email, etc.
        // Access inherited fields like observer.getName(), observer.getEmail() directly
        return ResponseEntity.ok("Observer registered successfully!");
    }
}

4. Database Integration (If Using JPA/Hibernate)

If you’re using JPA for database persistence, mark the parent User class with @MappedSuperclass to ensure its fields are included in the child entity’s database table:

import lombok.Data;
import jakarta.persistence.MappedSuperclass;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import java.time.LocalDateTime;

@Data
@MappedSuperclass
public class User {
    @NotBlank(message = "Name cannot be empty")
    private String name;
    
    @NotBlank(message = "Email cannot be empty")
    @Email(message = "Invalid email format")
    private String email;
    
    @NotBlank(message = "Password cannot be empty")
    private String password;
    
    private LocalDateTime createTime = LocalDateTime.now();
}

Then define the child entity with its own table-specific details:

import lombok.Data;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotBlank;

@Data
@Entity
public class Observer extends User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @NotBlank(message = "First name cannot be empty")
    private String firstname;
    
    @NotBlank(message = "Last name cannot be empty")
    private String lastname;
}

Key Notes to Keep in Mind

  • Stick to Logical Inheritance: Only use inheritance if the child class is a true subtype of the parent (e.g., Observer is a type of User). Avoid inheritance just for code reuse if the relationship doesn’t make sense.
  • Lombok Setup: Make sure your IDE has the Lombok plugin installed and enabled to avoid compilation errors with annotations like @Data.
  • Validation: You can add validation annotations directly to fields in both parent and child classes—Spring will enforce all constraints when processing requests.

内容的提问来源于stack exchange,提问作者alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:48:01