SpringBoot에서 Setter-Getter-Constructor
I’m happy to translate the article for you, but I’ll need the full text of the post (the sections you’d like translated). Could you please paste the article’s content here? Once I have it, I’ll keep the source line unchanged and provide a Korean translation while preserving all formatting, markdown, and code blocks.
왜 obj.setName("Rahul")을 사용하고 직접 obj.name = "Rahul"을 하지 않을까?
주요 이유 (3 목적)
| # | 이유 | 하지 않으면 어떻게 되는가 |
|---|---|---|
| 1 | 데이터 보안 – 필드가 public이면 누구나 잘못된 데이터를 넣을 수 있습니다. | Vendor v = new Vendor(); v.age = -500; // ❌ 잘못된 값이지만 Java 에러는 발생하지 않음 |
| 2 | 검증 – Setter 내부에서 데이터를 검사할 수 있습니다. | (예시는 아래를 참고하세요) |
| 3 | 캡슐화 – 필드를 변경하거나 읽기 위해 제어된 인터페이스를 제공합니다. | — |
- Setter → 데이터가 들어오기 전에 검증.
- Getter → 데이터를 올바른 형식으로 외부에 전달.
public class Vendor {
private int age;
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
this.age = age;
}
public int getAge() {
return age;
}
}
Spring Boot에서 Getter/Setter의 역할
- Jackson, Hibernate 등 라이브러리는 JavaBeans 규칙을 따릅니다.
- 필드가
public이고 Getter/Setter가 없으면 Spring Boot가 데이터를 JSON으로 변환하지 못하거나 DB에null이 설정됩니다.
비유 – Direct Variable = 집의 문을 열어 두는 것 (누구든 들어올 수 있음).
Getter/Setter = 문에 경비원을 배치하는 것.
Model Class (CloudVentor)를 다른 파일에서 사용하는 방법
1️⃣ Service 클래스에서 Constructor, Getter 및 Setter 사용
package com.restapi.demo.service;
import com.restapi.demo.model.CloudVentor;
import org.springframework.stereotype.Service;
@Service
public class CloudVendorService {
public void demoMethod() {
// ----- 1. CONSTRUCTOR -----
CloudVentor vendor1 = new CloudVentor("C1", "Amazon", "USA", "123456");
// ----- 2. GETTER -----
String name = vendor1.getVendorName();
System.out.println("Vendor का नाम है: " + name);
if (vendor1.getVendorAddress().equals("USA")) {
System.out.println("International Vendor है");
}
// ----- 3. SETTER -----
vendor1.setVendorPhoneNumber("9876543210");
// Empty‑constructor + setters
CloudVentor vendor2 = new CloudVentor(); // खाली ऑब्जेक्ट
vendor2.setVendorId("C2");
vendor2.setVendorName("Flipkart");
}
}
노트 – Spring Boot은 종종 Constructor나 Setter를 암시적으로 호출하지만, 응답을 보내기 위해서는 Getter가 필요합니다.
2️⃣ Controller에서 Hidden Magic (자동 바인딩)
package com.restapi.demo.controller;
import com.restapi.demo.model.CloudVentor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/cloudvendor")
public class CloudVendorAPIService {
private CloudVentor cloudVendor; // अस्थायी स्टोरेज (DB की जगह)
// ----- POST : JSON → Object (Constructor/Setter) -----
@PostMapping
public String createCloudVendorDetails(@RequestBody CloudVentor details) {
// आवश्यकता पड़ने पर मैन्युअल Setter
details.setVendorName(details.getVendorName().trim());
this.cloudVendor = details;
return "Cloud Vendor Created Successfully";
}
// ----- GET : Object → JSON (Getter) -----
@GetMapping("{vendorId}")
public CloudVentor getCloudVendorDetails(@PathVariable String vendorId) {
if (cloudVendor != null && cloudVendor.getVendorId().equals(vendorId)) {
return cloudVendor; // Getter कॉल हो कर JSON बनता है
}
return null;
}
}
메서드 유형 요약
| 메서드 | 언제 사용하나요? | 구문 예시 |
|---|---|---|
| Constructor | 새 객체를 처음 만들 때 | CloudVentor c1 = new CloudVentor("1","A","B","C"); |
| Getter | 데이터 읽기, 출력, 로직에 사용 | String n = c1.getVendorName(); |
| Setter | 객체 생성 후 데이터 변경 (업데이트) | c1.setVendorAddress("New Delhi"); |
전체 템플릿 – 한 클래스의 Getter/Setter/Constructor를 다른 클래스에서 사용하는 방법
// --------- Model (CloudVentor) ----------
package com.restapi.demo.model;
public class CloudVentor {
private String vendorId;
private String vendorName;
private String vendorAddress;
private String vendorPhoneNumber;
// ----- All‑args Constructor -----
public CloudVentor(String vendorId, String vendorName,
String vendorAddress, String vendorPhoneNumber) {
this.vendorId = vendorId;
this.vendorName = vendorName;
this.vendorAddress = vendorAddress;
this.vendorPhoneNumber = vendorPhoneNumber;
}
// ----- No‑args Constructor -----
public CloudVentor() {}
// ----- Getters -----
public String getVendorId() { return vendorId; }
public String getVendorName() { return vendorName; }
public String getVendorAddress() { return vendorAddress; }
public String getVendorPhoneNumber() { return vendorPhoneNumber; }
// ----- Setters -----
public void setVendorId(String vendorId) { this.vendorId = vendorId; }
public void setVendorName(String vendorName) { this.vendorName = vendorName; }
public void setVendorAddress(String vendorAddress) { this.vendorAddress = vendorAddress; }
public void setVendorPhoneNumber(String vendorPhoneNumber) {
this.vendorPhoneNumber = vendorPhoneNumber;
}
}
// --------- Service/Controller (उदाहरण) ----------
package com.restapi.demo.service; // या .controller
import com.restapi.demo.model.CloudVentor;
import org.springframework.stereotype.Service;
@Service
public class ExampleUsage {
public void demo() {
// Constructor
CloudVentor v = new CloudVentor("V01", "Amazon", "USA", "111222333");
// Getter
System.out.println("Name : " + v.getVendorName());
// Setter
v.setVendorPhoneNumber("999888777");
}
}
निष्कर्ष
- Getter/Setter 데이터의 보안 및 프레임워크 통합에 필요합니다.
- Direct field access는 검증이 이루어지지 않으며 Spring Boot 같은 도구가 데이터를 직렬화/역직렬화하지 못합니다.
이 원칙들을 이해하면 깨끗하고 안전하며 프레임워크‑프렌들리 코드를 작성할 수 있습니다. 🚀
1. 기본 구조 (모델 클래스)
Student.java (모델 클래스)
package com.example.demo.model;
public class Student {
private String id;
private String name;
private int age;
// 1. 기본 생성자 (No‑args)
public Student() {
}
// 2. 매개변수 생성자 (All‑args)
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// 3. Getter
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
// 4. Setter
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
Source: …
2. 이제 이 클래스를 다른 클래스에서 사용하기
Case 1 – Service 클래스에서 사용하기
StudentService.java (Business Logic)
package com.example.demo.service;
import com.example.demo.model.Student;
public class StudentService {
// 1. Constructor का Use (Object Create करने के लिए)
public Student createNewStudent() {
Student student = new Student("S1", "Rahul", 25); // Parameterized Constructor
return student;
}
// 2. Setter का Use (Data Modify करने के लिए)
public void updateStudentName(Student student, String newName) {
student.setName(newName); // Setter Call
}
// 3. Getter का Use (Data Read करने के लिए)
public void printStudentDetails(Student student) {
System.out.println("ID: " + student.getId()); // Getter Call
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());
}
}
Case 2 – Controller 클래스에서 사용하기 (Spring Boot REST API)
StudentController.java (API Endpoints)
package com.example.demo.controller;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/students")
public class StudentController {
private final StudentService studentService;
// Constructor Injection (Dependency)
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
// 1. GET API (Getter Use)
@GetMapping("/{id}")
public Student getStudent(@PathVariable String id) {
Student student = studentService.createNewStudent();
student.setId(id); // Setter Use
return student; // JSON에 자동 변환 (Getter Use)
}
// 2. POST API (Constructor + Setter Use)
@PostMapping
public Student addStudent(@RequestBody Student newStudent) {
// newStudent에 Request Body에서 데이터가 들어옴 (Jackson이 Setter/Constructor 사용)
System.out.println("New Student: " + newStudent.getName()); // Getter Use
return newStudent;
}
}
Case 3 – Main 클래스에서 사용하기 (Testing)
MainApplication.java (Test Class)
package com.example.demo;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
public class MainApplication {
public static void main(String[] args) {
// 1. Constructor Use (Object बनाना)
Student student1 = new Student("S1", "Amit", 22);
// 2. Setter Use (Data Change करना)
student1.setAge(23);
// 3. Getter Use (Data Read करना)
System.out.println("Name: " + student1.getName());
// Service Class का Use
StudentService studentService = new StudentService();
Student student2 = studentService.createNewStudent();
studentService.printStudentDetails(student2);
}
}
3. Lombok 사용법 (수동 Getter/Setter를 작성하고 싶지 않을 때)
Student.java (Lombok 버전)
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
@Data // Auto‑generates getters, setters, toString, equals, hashCode
@NoArgsConstructor // Default Constructor
@AllArgsConstructor // Parameterized Constructor
public class Student {
private String id;
private String name;
private int age;
}
이제 코드를 별도로 작성하지 않고 student.getId(), student.setName("Rahul") 같은 메서드를 사용할 수 있습니다!
4. Java Records 사용 (불변 객체를 위해)
StudentRecord.java (불변 DTO)
public record StudentRecord(String id, String name, int age) {}
- 자동 생성된 getter:
id(),name(),age() - setter 없음 (불변)
- 사용 사례: API 응답, 설정 데이터, DTOs
5. 결론 (Conclusion)
| Use Case | 어떻게 사용하나요? |
|---|---|
| Model Class (JPA Entity) | 전통적인 클래스 + Lombok (@Data) |
| REST API DTOs | Java Records (불변) or Lombok |
| Service/Controller Logic | Getter / Setter / Constructor 호출 |
| Testing (Main Class) | new Student() + setX() + getX() |
Recommendation
- Spring Boot + JPA → Lombok (
@Data) - API DTOs → Java Records
- Manual control → 전통적인 getter/setter
이렇게 하면 어떤 클래스에서도 getter, setter, 그리고 constructor를 쉽게 사용할 수 있습니다! 🚀