While implementing a partial update (PATCH) API in a Spring Boot service layer, I used Spring’s ReflectionUtils.findRequiredField() to dynamically update entity fields. Instead of writing multiple conditional setter calls, I leveraged Java Reflection to update only the fields provided in the request. Field field = ReflectionUtils.findRequiredField(Employee.class, fieldName); field.setAccessible(true); ReflectionUtils.setField(field, employee, value); Why I used findRequiredField: 1. Ensures the field must exist in the entity 2. Follows a fail-fast approach (throws exception if field is missing) 3. Keeps service-layer logic clean and generic 4. Ideal for controlled/internal PATCH operations. Key takeaway: findRequiredField() is best used when field names are validated or predefined, while findField() is safer for untrusted user inputs. This approach helped me reduce boilerplate code and improve maintainability in Spring Boot applications. #Reflection bypass encapsution, so it should be used carefully with proper validation and type handling. #Java #SpringBoot #Reflection #RESTAPI #PATCH #BackendDevelopment #Microservices #CleanCode #LearningJourney
Spring Boot PATCH API with ReflectionUtils
More Relevant Posts
-
@Autowired & @Qualifier in Spring Framework 👇 In the Spring Framework, @Autowired and @Qualifier are used for Dependency Injection. 🔹 @Autowired @Autowired is used to automatically inject dependencies into a class. The Spring IoC container finds and connects the required bean without manually creating objects using new. ✅ Why use @Autowired? Reduces boilerplate code Removes manual object creation Supports loose coupling Makes code cleaner and more readable 📌 Where can we use @Autowired? On Constructor (Recommended ✅) On Setter methods On Fields 🔹 @Qualifier @Qualifier is used along with @Autowired when multiple beans of the same type exist. It helps Spring identify which exact bean should be injected. ✅ Why use @Qualifier? Resolves ambiguity Provides better control over bean selection Makes configuration more precise 📌 Where can we use @Qualifier? In class-based (annotation-based) configuration On Constructor parameters On Setter methods On Fields 👉 In simple words: @Autowired performs injection @Qualifier selects the correct bean Together, they make Spring applications clean, flexible, and well-structured. 📚 Currently learning & implementing concepts step by step. #Spring #Autowired #Qualifier #DependencyInjection #IOC #SpringFramework #Java #BackendDevelopment #JavaFullStack #Day13_Adv_Java
To view or add a comment, sign in
-
-
⏱️ How much time does System.out.println() actually take? (You might be surprised) Most of us use System.out.println() everywhere — for debugging, logging, and quick checks. But have you ever asked: how expensive is it? 🧠 The short answer System.out.println() is slow compared to normal Java operations. ⏳ On average: 1–5 milliseconds per call (can be more) Depends on OS, console, and I/O buffering That may look small… until you put it inside a loop. ⚠️ Why is it slow? Because System.out.println(): 🔹 Writes to I/O stream (not memory) 🔹 Is synchronized (thread-safe → slower) 🔹 Flushes output to the console 🔹 Waits for the OS to handle the write This is thousands of times slower than in-memory operations. 🔁 Real impact for(int i = 0; i < 10000; i++) { System.out.println(i); } 👉 This can take seconds, not milliseconds. Now imagine this inside: REST APIs Microservices High-traffic applications 😬 ✅ What to do instead? ✔️ Use logging frameworks (Logback, Log4j2) ✔️ Log at proper levels (DEBUG, INFO) ✔️ Avoid console printing in production code 🏁 Final thought System.out.println() is great for learning and quick debugging, but in real applications — it can silently kill performance. 🔔 Follow for more insights on Java internals & backend performance 🚀 #Java #JavaDeveloper #CoreJava #AdvancedJava #JavaProgramming #Spring #SpringBoot #Hibernate #JPA #BackendDevelopment #Microservices #RESTAPI #SoftwareEngineering #CleanCode #TechLearning #CodingJourney #Programming
To view or add a comment, sign in
-
-
Spring Boot Annotation Cheat Sheet 📝 Stop memorizing and start understanding the "Magic" behind the framework. Here are the 10 essentials every Backend Developer should know: ⦿ @SpringBootApplication: The application entry point (Config + Auto-Config + Component Scan). ⦿ @Configuration: Marks a class as a source of bean definitions. ⦿ @PathVariable: Extracts values directly from the URI path. ⦿ @RequestBody: Maps the HttpRequest body to a transfer object (DTO). ⦿ @Autowired: Powers Dependency Injection Constructor injection is best!. ⦿ @RestController: Handles HTTP requests and returns JSON responses. ⦿ @Bean: Tells Spring that a method returns an object to be managed as a bean. ⦿ @EnableAutoConfiguration: Guesses and configures beans based on your classpath. ⦿ @Component: A generic stereotype for any Spring-managed component. ⦿ @Repository: Defines the Data Access layer and handles DB exceptions. The Drawback: Heavy use of annotations can lead to "Magic Fatigue." Behind every annotation is a Java proxy, understanding the why is just as important as the what. #Java #SpringBoot #BackendDevelopment #LearningInPublic #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🚨 Your favourite collection might be your biggest bottleneck. We’ve all been there — we start out with ArrayList. It’s simple, fast, and works well for most cases. But as your application grows, that one-size-fits-all approach quietly becomes the reason for mysterious slowdowns. The Java Collections Framework (JCF) isn’t a buffet of similar options — it’s a power toolset designed for specific trade-offs. Knowing which one to pick can make your system faster and your code cleaner. Here’s a quick reality check 👇 ArrayList ➡️ Great for fast random access and cheap appends; but costly middle inserts or deletes. LinkedList ➡️ Best for frequent head/tail updates; but worse cache locality and higher memory cost. HashMap / HashSet ➡️ O(1) lookups; but no ordering, and hash collisions can bite you if keys aren’t well-designed. LinkedHashMap ➡️ Preserves insertion order — perfect for caches or predictable APIs. TreeMap / TreeSet ➡️ Keeps keys sorted; excellent when order matters more than speed. ⚙️ A few pro tips: Use ArrayList for “read-mostly” lists. If you’re iterating more than mutating, it’s your go-to. Avoid LinkedList unless you really need it. In most modern JVMs, it’s slower due to poor cache performance. Use EnumMap or EnumSet when keys are enums — highly memory and speed efficient. Initialize collection sizes upfront. Helps avoid resizing overhead, especially in tight loops. Prefer immutability — List.of() and Map.of() are your friends for static data. Choosing the right collection isn’t a micro-optimization — it’s a design decision that compounds as your system scales. So, what do you think? 👉 Which Java collection is overused or misused most in your experience? #Java #CollectionsFramework #DataStructures #Performance #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
📌 Spring Boot Annotation Series – Part 8 ✅ @Component annotation The @Component annotation is used to mark a class as a Spring-managed bean 👇 🔹 Why do we use @Component? To tell Spring: 👉 “Create an object of this class and manage it.” - To enable dependency injection - To let Spring detect the class during component scanning 🔹 How does it work? When Spring Boot starts: - It scans packages (using @ComponentScan) - Finds classes annotated with @Component - Creates and registers them as beans in the Spring container 🔹 Simple example @Component public class EmailService { public void sendEmail() { System.out.println("Email sent"); } } Now this class can be injected using: @Autowired private EmailService emailService; 🔹 In simple words @Component tells Spring to automatically create and manage this class as a bean. 👉 🧠 Quick Understanding - Marks a class as a Spring bean - Detected during component scanning - Enables dependency injection #SpringBoot #Java #Component #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
I just published Part 7 of my Spring Boot series. This installment focuses on making your APIs professional and production-ready by effectively handling errors and validating requests. In this article, I cover: ✔️ Why exception handling matters ✔️ Custom exceptions (e.g., ResourceNotFoundException) ✔️ Global exception handling with @RestControllerAdvice ✔️ Request validation using @Valid, @NotBlank, @Email ✔️ Returning clean 400/404 JSON responses instead of messy errors Read here. #SpringBoot #Java #RESTAPI #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 13/100 - Spring Boot Annotations - 4️⃣ @Configuration & @Bean ➡️ @Configuration 🔹What is it - A class-level annotation which tells Spring that this class contains bean definitions for the IoC container. - It is a modern replacement for XML-based configuration. 🔹Why to use - Makes configuration type-safe - Easy to read and maintain - Fully Java-based (no XML) ➡️ @Bean 🔹What is it - A method-level annotation used inside a @Configuration class to explicitly create and register a bean in the Spring container. 🔹Why to use - Useful when you cannot modify a class (e.g., third-party libraries) - Gives full control over object creation and configuration 📌 Key Takeaway @Configuration → where beans are defined @Bean → how a bean is created Next post: https://lnkd.in/d3pztG-x Previous post: https://lnkd.in/d8NzCVkB #100Days #SpringBoot #Java #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🚦 Spring Boot Simplified: @Primary vs. @Qualifier 🚦 Ever found yourself with multiple beans of the same type in your Spring application and wondered how Spring knows which one to inject? 🤔 🌟 @Primary Think of this as setting a default. If multiple beans of a type exist, the one marked with @Primary is the one Spring picks—unless told otherwise. @Bean @Primary public DataSource primaryDataSource() { // ... } ✨ @Qualifier Want to be more explicit? Use @Qualifier to specify exactly which bean you want, by name! @Autowired @Qualifier("secondaryDataSource") private DataSource dataSource; 🔑 Key Takeaway: Use @Primary for a sensible default. Use @Qualifier for precision control. These annotations give you the flexibility to manage complex dependency graphs cleanly and clearly—making your codebase more robust and readable! #SpringBoot #Java #CodingTips #BeanInjection #SoftwareEngineering #SpringFramework
To view or add a comment, sign in
-
The moment Java systems begin handling snapshots, events, concurrent state, or domain aggregates, object copying stops being trivial. This is where the Copy Constructor approach becomes essential. A copy constructor gives developers: 🔹 full control over what gets duplicated 🔹 guaranteed avoidance of Cloneable's broken contract 🔹 clear semantics for nested objects 🔹 deterministic behavior under concurrency 🔹 predictable memory and lifecycle boundaries clone() suffers from reflection, shallow copying traps, CloneNotSupportedException, and inheritance fragility. Copy constructors avoid all of this by tying copying logic directly to the domain — not to a runtime mechanism. The result is a design where every replicated object is intentional, safe, and structurally consistent. This is exactly what high-integrity systems — financial flows, rule engines, schedulers, auditing pipelines — depend on. When correctness matters, explicit copying wins. Hashtags: #Java #CopyConstructor #AdvancedJava #JavaInternals #BackendEngineering #CleanArchitecture #ObjectOrientedDesign #CodeQuality #SoftwareEngineering #ConcurrencyControl #Immutability #ProgrammingBestPractices #DeepWork #JavaCommunity #HighPerformanceJava #TechLearning
To view or add a comment, sign in
-
🌱 My Spring Journey : Dependency Lookup -> Here, the target class writes the logic to obtain the dependent class object, and for this it uses the getBean(..) method. -> If the dependent class object is required in multiple methods of the target class, we should prefer Dependency Injection; otherwise, we can go for Dependency Lookup. Limitations of Dependency Lookup : -> For this approach, we need to create or access an extra IOC container inside the business method of the target class. -> Due to this, even singleton-scoped Spring beans may get pre-instantiated multiple times (when multiple containers are created). -> This extra IOC container creation process generates in-memory metadata for the Spring bean configuration files, which can lead to memory issues. -> To overcome this problem we can use Interface injection #SpringFramework #DependencyLookup #DependencyInjection #Java #SpringCore #BackendDevelopment #LearningJourney
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development