🚨 Why I stopped using field injection in Spring Boot I used to write this: @Autowired private UserService userService; Looks clean… but caused real issues. ❌ Problems: * Hard to test * Hidden dependencies * NullPointer risks in edge cases ✅ Now I always use constructor injection: public UserController(UserService userService) { this.userService = userService; } 💥 Real benefit: While writing unit tests, I realized I could mock dependencies easily without Spring context. 💡 Takeaway: Field injection is convenient. Constructor injection is production-safe. Small change. Big impact. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #Microservices #RESTAPI #SystemDesign #DeveloperLife #100DaysOfCode
Ditching Field Injection for Constructor Injection in Spring Boot
More Relevant Posts
-
🧠 After learning the Spring Bean Lifecycle, I explored another powerful concept today 👀 Singleton vs Prototype Bean Scope in Spring Boot 🚀 The default scope in Spring is singleton 👇 ✅ Only one object instance is created ✅ Shared across the whole application ✅ Best for services, repositories, controllers Then comes prototype 👇 🔁 A new object is created every time it is requested This makes it useful for: ✅ temporary objects ✅ stateful helpers ✅ per-request custom processing 💡 My takeaway: Bean scope directly changes how Spring manages memory and object reuse. Small annotations can completely change runtime behavior ⚡ #Java #SpringBoot #BeanScope #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
🧠 After learning Dependency Injection, I had one big question 👀 Who actually creates these objects in Spring Boot, and when? Today I explored the Spring Bean Lifecycle 🚀 Simple flow 👇 1️⃣ Spring container starts 2️⃣ Bean object is created 3️⃣ Dependencies are injected 4️⃣ Bean becomes ready to use 5️⃣ Bean is destroyed when the app shuts down What made this even more interesting 👇 ✅ @PostConstruct → runs after bean creation ✅ @PreDestroy → runs before bean cleanup 💡 My takeaway: Spring doesn’t just inject dependencies — it also manages the entire lifecycle of the object. The more I learn this framework, the more beautifully engineered it feels ⚡ #Java #SpringBoot #BeanLifecycle #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 20/100: Spring Boot From Zero to Production Topic: Custom Auto-Configuration We covered Auto-Configuration. We covered disabling it. But does it stop there? Nope. 👀 Spring Boot lets you build your own auto-configuration too. 🔧 But, How It Works? You create a @Configuration class and slap conditionals on it. Spring Boot only loads it if your conditions are met. Two most common ones: @ConditionalOnClass → Load only if a class exists on the classpath @ConditionalOnProperty → Load only if a property is set in application.properties 💡 See the code attached below. ⬇️ No DataSource on classpath? → Skipped entirely db.enabled=false? → Skipped entirely Bean already defined by user? → Your default is skipped ✅ 📌 Don't forget to register it In META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -> com.yourpackage.MyDataAutoConfiguration Without this, Spring Boot won't pick it up. Checkout the previous posts on Auto-Config & disabling it to better understand the sequence. See you in the next one! #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend #AutoConfiguration
To view or add a comment, sign in
-
-
#Post7 In the previous post, we saw how to handle exceptions globally using @ControllerAdvice. Now let’s take it one step further 👇 How do we handle specific errors properly? That’s where Custom Exceptions come in 🔥 Instead of using generic exceptions, we can create our own exception based on the use case. Example: public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } } 👉 Now we can throw this exception when user is not found Example usage: if(user == null){ throw new UserNotFoundException("User not found"); } 💡 Why use Custom Exceptions? • Better error clarity • Easy debugging • More control over API responses Key takeaway: Use custom exceptions to make your API errors more meaningful and structured 👍 In the next post, we will understand validation using @Valid 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
🚀 Understanding Dependency Injection in Spring Boot with a Simple Example I recently explored one of the core concepts of the Spring Framework — Dependency Injection (DI) — by building a simple Spring Boot application. 💡 What is Dependency Injection? Dependency Injection is a design pattern where the Spring container automatically provides the required dependencies to a class, instead of the class creating them manually. This helps in achieving loose coupling and better maintainability. 🔷 Project Overview In this example, I created: A Developer class that depends on a Computer A Computer interface with multiple implementations: Laptop Desktop 🔷 How it Works ✔️ The Developer class uses @Autowired to inject the dependency: Spring automatically assigns an object of a class that implements Computer ✔️ Since there are multiple implementations (Laptop & Desktop): I used @Primary on the Laptop class This tells Spring to inject Laptop by default ✔️ The application flow: Spring Boot starts and initializes the application context Beans are created automatically using @Component Dependency is injected into the Developer class The startCoding() method executes and calls computer.code() 🔷 Key Annotations Used @SpringBootApplication → Entry point of the application @Component → Marks classes as Spring beans @Autowired → Injects dependencies automatically @Primary → Resolves ambiguity when multiple beans are available 🔷 Output 👉 "Coding in laptop......" (Because Laptop is marked as @Primary) ✨ This small implementation helped me clearly understand how Spring manages dependencies behind the scenes. #SpringBoot #Java #DependencyInjection #BackendDevelopment Thanks to Anand Kumar Buddarapu Sir.
To view or add a comment, sign in
-
🧠 After learning Request Scope, I explored something even more practical today 👀 **Session Scope in Spring Boot** 🌐 Here’s the simple idea 👇 ✅ One bean instance is created per **user session** ✅ The same object is reused across multiple requests from the same user ✅ Different users get different objects This makes it useful for 👇 🔹 user login data 🔹 shopping cart 🔹 session-based preferences 🔹 multi-step workflows 💡 Quick difference: Request Scope → new object every request Session Scope → same object for the same user 💡 My takeaway: Session scope helps maintain **user-specific state across multiple requests** without recreating objects again and again ⚡ #Java #SpringBoot #SessionScope #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Spent 10 minutes wondering why my Spring Boot application was not picking up environment variables. The code looked fine: @Value("${DATABASE_URL}") private String databaseUrl; No errors at startup. But the value was always null. The problem: I was using underscores in the property name, but Spring expects dots or lowercase with hyphens. The fix: @Value("${database.url}") private String databaseUrl; And in application_properties: database.url=${DATABASE_URL} One mapping. That was it. Spring does not automatically convert environment variable names to property names. You need to map them explicitly. What environment variable issue has caught you off guard? #Java #SpringBoot #EnvironmentVariables #Debugging #BackendDevelopment
To view or add a comment, sign in
-
Spring Boot Circular Dependency — Dangerous issue ⚠️ Example: Service A → depends on Service B Service B → depends on Service A 👉 Boom 💥 Circular dependency error 💡 Why it happens: Poor design & tight coupling Solutions 👇 ✅ Refactor logic ✅ Use constructor injection properly ✅ Introduce third service ✅ Use @Lazy (temporary fix) ⚠️ Avoid: Field injection (hard to debug) 👉 Best practice: Use constructor injection ALWAYS Clean architecture prevents these issues 🔥 #SpringBoot #Java #CleanCode
To view or add a comment, sign in
-
Understanding Request Mapping in Spring Boot While working on my Spring Boot projects, I explored how request mapping plays a crucial role in handling client requests efficiently. 🔹 @RequestMapping This is a general-purpose annotation used to map HTTP requests to handler methods. It can be applied at both class and method level and supports multiple HTTP methods. 🔹 @GetMapping Specifically designed for handling HTTP GET requests. It makes the code more readable and is commonly used for fetching data from the server. 🔹 @PostMapping Used for handling HTTP POST requests. Ideal when sending data from client to server, such as form submissions or creating new records. Why use specific mappings? Using @GetMapping, @PostMapping, etc., improves code clarity and makes APIs more expressive compared to using @RequestMapping for everything. In real projects, choosing the right mapping annotation helps in building clean and maintainable REST APIs. #SpringBoot #Java #BackendDevelopment #RESTAPI #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
Healthy services can still create a broken system. That lesson took me longer to learn than it should have. Early on, I used to judge systems service by service: Is inventory up? Is pricing up? Is payment up? But production does not care whether each box is green in isolation. It cares about the full request path. That changed how I look at failures, tracing, retries, and resilience. A lot of systems are not failing at the component level. They are failing at the interaction level. What taught you that lesson? #Java #SpringBoot #DistributedSystems #Microservices #BackendEngineering
To view or add a comment, sign in
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