SETTER-GETTER-CONSTRUCTOR IN SPRINGBOOT
Source: Dev.to
क्यों obj.setName("Rahul") और सीधे obj.name = "Rahul" नहीं करते?
मुख्य कारण (3 Purpose)
| # | कारण | क्या होता है अगर नहीं करते |
|---|---|---|
| 1 | डेटा सुरक्षा – यदि फ़ील्ड public हो तो कोई भी गलत डेटा डाल सकता है। | Vendor v = new Vendor(); v.age = -500; // ❌ गलत, लेकिन Java error नहीं देता |
| 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 या Setters को इम्प्लिसिटली कॉल करता है, लेकिन Response भेजने के लिए 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 | ऑब्जेक्ट बनने के बाद डेटा बदलना (Update) | 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. Basic Structure (Model Class)
Student.java (Model Class)
package com.example.demo.model;
public class Student {
private String id;
private String name;
private int age;
// 1. Default Constructor (No‑args)
public Student() {
}
// 2. Parameterized Constructor (All‑args)
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// 3. Getters
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
// 4. Setters
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
2. अब इस Class को दूसरी Class में Use करें
Case 1 – Service Class में Use करना
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 Class में Use करना (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 में auto‑convert (Getter Use)
}
// 2. POST API (Constructor + Setter Use)
@PostMapping
public Student addStudent(@RequestBody Student newStudent) {
// newStudent में Request Body से data आया (Jackson ने Setter/Constructor Use किया)
System.out.println("New Student: " + newStudent.getName()); // Getter Use
return newStudent;
}
}
Case 3 – Main Class में Use करना (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 का Use (अगर Manual Getter/Setter नहीं लिखना चाहते)
Student.java (Lombok Version)
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 का Use (Immutable Objects के लिए)
StudentRecord.java (Immutable DTO)
public record StudentRecord(String id, String name, int age) {}
- Auto‑generated getters:
id(),name(),age() - No setters (Immutable)
- Use case: API responses, configuration data, DTOs
5. निष्कर्ष (Conclusion)
| Use Case | कैसे Use करें? |
|---|---|
| Model Class (JPA Entity) | Traditional class + Lombok (@Data) |
| REST API DTOs | Java Records (Immutable) or Lombok |
| Service/Controller Logic | Getter / Setter / Constructor calls |
| Testing (Main Class) | new Student() + setX() + getX() |
Recommendation
- Spring Boot + JPA → Lombok (
@Data) - API DTOs → Java Records
- Manual control → Traditional getters/setters
इस तरह आप किसी भी class में getters, setters, और constructors का उपयोग आसानी से कर सकते हैं! 🚀