DEV Community

Er. Bhupendra
Er. Bhupendra

Posted on

SETTER-GETTER-CONSTRUCTOR IN SPRINGBOOT

आसान भाषा में समझाता हूँ। आपका सवाल बहुत सही है: "सीधा variable use क्यों नहीं कर लेते? obj.name = 'Rahul'? ये obj.setName('Rahul') का नाटक क्यों?"

इसके 3 मुख्य मकसद (Purpose) हैं:

1. सुरक्षा और कंट्रोल (Security & Validation) - सबसे बड़ा कारण

अगर आप Variable को public छोड़ दें, तो कोई भी उसमें गलत डेटा डाल सकता है।

बिना Setter के (गलत तरीका):

public class Vendor {
    public int age;
}

// Main file me:
Vendor v = new Vendor();
v.age = -500; // ❌ Ghalat! Insaan ki age negative nahi ho sakti, par Java error nahi dega.
Enter fullscreen mode Exit fullscreen mode

Setter के साथ (सही तरीका):
Setter एक Security Guard की तरह काम करता है। वह डेटा सेट करने से पहले चेक कर सकता है।

public class Vendor {
    private int age;

    public void setAge(int age) {
        if (age < 0) {
            System.out.println("Error: Age negative nahi ho sakti!");
        } else {
            this.age = age; // ✅ Sahi data hi save hoga
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

फायदा: Setter गलत डेटा को सिस्टम में घुसने से रोकता है।


2. डेटा को Read-Only या Write-Only बनाना

कभी-कभी हम चाहते हैं कि डेटा दिखे, लेकिन कोई उसे बदल न सके। या डेटा बदला जा सके, लेकिन दिखे नहीं।

  • Read-Only: अगर आप केवल Getter बनाएंगे और Setter नहीं बनाएंगे, तो कोई भी डेटा पढ़ तो सकेगा, लेकिन बदल नहीं पाएगा (जैसे: vendorId जो एक बार सेट हो गया तो बदलना नहीं चाहिए)।
  • Write-Only: अगर आप केवल Setter बनाएंगे (जैसे: password), तो यूजर पासवर्ड सेट कर सकता है, लेकिन getPassword() नहीं होगा तो कोई पासवर्ड देख नहीं पाएगा।

3. Spring Boot और Tools की मजबूरी (Framework Requirement)

यह टेक्निकल कारण है। Spring Boot में बहुत सारी Libraries हैं (जैसे Jackson जो JSON बनाती है, Hibernate जो Database चलाता है)।

ये Libraries इंसानों की तरह कोड नहीं पढ़तीं। ये एक नियम (Standard) फॉलो करती हैं जिसे Java Beans Standard कहते है��।

  • इनका नियम है: "अगर मुझे डेटा पढ़ना है, तो मैं get वाला method ढूँढूँगी। अगर मुझे डेटा डालना है, तो मैं set वाला method ढूँढूँगी।"
  • अगर आप Variable को public कर दें और Getter/Setter न बनाएं, तो Spring Boot अक्सर आपका डेटा JSON में कन्वर्ट नहीं करेगा या Database में null वैल्यू चली जाएगी।

Summary (निचोड़)

  1. Direct Variable: घर का दरवाजा खुला छोड़ना (कोई भी आए, कुछ भी रखे/उठाए)।
  2. Getter/Setter: घर पर दरवाजा लगाकर Guard (Watchman) बैठाना।
    • Setter का मकसद: चेक करना कि जो अंदर आ रहा है वो सही है या नहीं।
    • Getter का मकसद: डेटा को सही ढंग से बाहर भेजना।

दूसरी फाइल (जैसे कि Controller या Service class) में Model class (CloudVentor) का इस्तेमाल कैसे होता है, इसे समझने के लिए नीचे दिए गए 2 तरीके देखें।

यहाँ हम मान रहे हैं कि आपकी CloudVentor क्लास com.restapi.demo.model पैकेज में है।

Scenario 1: Basic Java Logic (Service Layer)

यहाँ हम देखेंगे कि हम खुद कोड लिखकर Constructor, Getter और Setter को कैसे call करते हैं।

package com.restapi.demo.service;

// 1. Apni Model class ko import karna padega
import com.restapi.demo.model.CloudVentor;
import org.springframework.stereotype.Service;

@Service
public class CloudVendorService {

    public void demoMethod() {

        // --- 1. CONSTRUCTOR KA USE ---
        // Naya object banane ke liye
        // Syntax: ClassName obj = new ClassName(values...);
        CloudVentor vendor1 = new CloudVentor("C1", "Amazon", "USA", "123456");


        // --- 2. GETTER KA USE ---
        // Object ke andar se data padhne (read) ke liye
        // Syntax: obj.getMethodName();
        String name = vendor1.getVendorName();
        System.out.println("Vendor ka naam hai: " + name);

        // Logic lagane ke liye getter use hota hai
        if(vendor1.getVendorAddress().equals("USA")) {
            System.out.println("International Vendor hai");
        }


        // --- 3. SETTER KA USE ---
        // Bane hue object ka data badalne (update) ke liye
        // Syntax: obj.setMethodName(newValue);

        // Maan lo vendor ka phone number change ho gaya
        vendor1.setVendorPhoneNumber("9876543210");

        // Empty constructor ke sath Setter ka use
        CloudVentor vendor2 = new CloudVentor(); // Empty object bana
        vendor2.setVendorId("C2");               // Baad me value set ki
        vendor2.setVendorName("Flipkart");
    }
}
Enter fullscreen mode Exit fullscreen mode

Scenario 2: Spring Boot Controller (Real API Use)

Spring Boot में अक्सर हम Setter और Constructor को implicitly (बिना दिखे) use करते हैं, लेकिन Getter को response भेजने के लिए use करते हैं।

package com.restapi.demo.controller;

import com.restapi.demo.model.CloudVentor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/cloudvendor")
public class CloudVendorAPIService {

    CloudVentor cloudVendor; // Database ki jagah abhi temporary variable use kar rahe hain

    // --- CONSTRUCTOR & SETTER (Hidden Magic) ---
    // Jab Frontend se JSON aata hai, Spring Boot khud
    // Constructor ya Setters ko call karke ye object 'details' ready karta hai.
    @PostMapping
    public String createCloudVendorDetails(@RequestBody CloudVentor details) {

        // Hum yaha manual SETTER use kar sakte hain agar kuch modify karna ho
        // Maan lo user ne naam bheja "  amazon  " aur hume trim karna hai
        details.setVendorName(details.getVendorName().trim());

        this.cloudVendor = details;
        return "Cloud Vendor Created Successfully";
    }

    // --- GETTER (Hidden Magic) ---
    // Jab hum object return karte hain, Spring Boot
    // Getters (getVendorName, getVendorId etc.) ko call karke JSON banata hai.
    @GetMapping("{vendorId}")
    public CloudVentor getCloudVendorDetails(@PathVariable String vendorId) {

        // Yaha hum GETTER use kar rahe hain check karne ke liye
        if(cloudVendor.getVendorId().equals(vendorId)) {
            return cloudVendor; // Iske getters call honge aur JSON banega
        } else {
            return null;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Summary: कब क्या Use करें?

Method Type कब Use करें? Syntax Example
Constructor जब पहली बार नया Object बनाना हो (Example: new CloudVentor(...)). CloudVentor c1 = new CloudVentor("1", "A", "B", "C");
Getter जब Object के अंदर का डेटा देखना हो, प्रिंट करना हो, या Logic (if/else) लगाना हो। String n = c1.getVendorName();
Setter जब Object बनने के बाद उसका कोई डेटा बदलना (Update/Modify) करना हो। c1.setVendorAddress("New Delhi");

Getter, Setter, और Constructor का दूसरी Class/Files में Use करने का तरीका

यहां मैं आपको पूरा टेम्प्लेट दूंगा कि कैसे आप एक class के getters, setters, और constructors को दूसरी class में use कर सकते हैं।


1. Basic Structure (Model Class)

मान लीजिए हमारे पास एक Student.java (Model Class) है जिसमें getters, setters, और constructors हैं:

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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());
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Lombok का Use (अगर Manual Getter/Setter नहीं लिखना चाहते)

अगर आप बिना manual getter/setter लिखे यही functionality चाहते हैं, तो Lombok use कर सकते हैं:

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;
}
Enter fullscreen mode Exit fullscreen mode
  • अब आप बिना कुछ लिखे student.getId(), student.setName("Rahul") जैसे methods use कर सकते हैं!

4. Java Records का Use (Immutable Objects के लिए)

अगर data create होने के बाद modify नहीं होना चाहिए, तो Java Records use करें:

StudentRecord.java (Immutable DTO)

public record StudentRecord(String id, String name, int age) {}
Enter fullscreen mode Exit fullscreen mode
  • 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) या 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 का use कर सकते हैं! 🚀

Top comments (0)