🚀 Day 10/100: Spring Boot From Zero to Production Topic: Bean Scopes 🧩 Remember when we talked about Beans in Java? Quick recap: Beans are just instances of your classes that live inside the Spring Container. Spring manages their lifecycle and handles Dependency Injection so you don't have to manually "new" them up every time. But there is a lot more to it than just creating them. We need to talk about Bean Scopes. 1. The Default: Singleton By default, all beans in Spring are Singletons. This means Spring creates the instance once and shares that same exact instance every single time it’s needed. For components like Services, Repositories, or Controllers, a single instance is perfect because they are usually stateless they just perform actions. 2. The Alternative: Prototype But what if a single instance isn't enough? What if your bean holds state-specific data or thread-specific info where one user's data shouldn't leak into another's? That’s where the Prototype scope comes in. With this, Spring creates a brand-new instance every time the bean is requested. ⚠️ Word of caution: Use this wisely! Creating too many prototype beans when they aren't needed can put a heavy load on your memory. 3. Web-Aware Scopes If you are building web apps, Spring offers even more specialized scopes: Request Scope: A new bean for every single HTTP request. Session Scope: A bean that lives as long as the user's HTTP session. Choosing the right scope is all about balancing memory efficiency with data integrity. How do you usually decide between Singleton and Prototype in your projects? Let’s discuss below! 👇 #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
Spring Boot Bean Scopes: Singleton vs Prototype
More Relevant Posts
-
🚀 @RequestBody & @ResponseBody — The Magic Behind JSON in Spring Boot Most developers use these annotations daily without thinking about what actually happens under the hood. Let me change that. When a client sends JSON to your REST API, Spring Boot doesn't magically "just know" how to convert it into a Java object. That's @RequestBody at work — it tells the HttpMessageConverter (Jackson, by default) to deserialize the incoming JSON stream into your method parameter. @PostMapping("/users") public ResponseEntity<UserResponse> createUser( @RequestBody UserRequest request) { // 'request' is fully populated from JSON body return ResponseEntity.status(201) .body(service.create(request)); } @ResponseBody does the reverse — it serializes your return value into JSON and writes it directly to the HTTP response. When you use @RestController, @ResponseBody is already included. That's the only difference between @Controller and @RestController. What actually happens: 1. Request arrives → DispatcherServlet routes it 2. HttpMessageConverter checks Content-Type: application/json 3. Jackson's ObjectMapper deserializes JSON → Java object 4. Your method runs 5. Return value → ObjectMapper serializes → JSON response Common pitfalls: • Missing Content-Type: application/json header → 415 Unsupported Media Type • No default constructor on your DTO → deserialization fails • Field names mismatch (use @JsonProperty to fix) #Java #SpringBoot #BackendDevelopment #REST #API #SoftwareEngineering
To view or add a comment, sign in
-
Hi everyone 👋 Continuing the Spring Boot Annotation Series 👇 📌 Spring Boot Annotation Series Part 25 – @ModelAttribute @ModelAttribute is used to bind request data (form data / query params) to a Java object. It is part of the Spring Framework and mainly used in Spring MVC applications. 🔹 Why do we use @ModelAttribute? When we receive multiple values from a request (like form data), instead of handling each parameter separately, we can bind them directly to an object. 👉 Makes code clean and structured. 🔹 Where is it used? Form submissions (HTML forms) Query parameters MVC applications (not mostly REST APIs) 🔹 In Simple Words @ModelAttribute takes request data and converts it into a Java object. 👉 🧠 Quick Understanding Binds request data to object Used in form handling Works with query/form data Not mainly used for JSON #SpringBoot #Java #ModelAttribute #SpringMVC #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
Hi everyone 👋 Continuing the Spring Boot Annotation Series 👇 📌 Spring Boot Annotation Series part 24 – @ResponseBody @ResponseBody is used to return data directly in the HTTP response body instead of returning a view (HTML page). It is part of the Spring Framework and is commonly used in REST APIs built with Spring Boot. 🔹 Why do we use @ResponseBody? In Spring MVC: Without @ResponseBody → returns a view (HTML/JSP) With @ResponseBody → returns data (JSON/XML) 👉 It is mainly used for building REST APIs. 🔹 Simple Example @Controller public class UserController { @GetMapping("/user") @ResponseBody public String getUser() { return "User details"; } } 👉 Output will be directly shown in response body, not a view. 🔹 Returning Object as JSON @GetMapping("/user") @ResponseBody public User getUser() { return new User(1, "Asmita"); } 👉 Spring automatically converts it into JSON. 🔹 How does it work? - Spring uses Jackson library internally - Converts Java object → JSON - Sends it in HTTP response 🔹 In Simple Words @ResponseBody tells Spring to send data directly in the response instead of returning a web page. 👉 🧠 Quick Understanding - Returns data, not view - Converts object → JSON - Used in REST APIs - Not needed with @RestController #SpringBoot #Java #ResponseBody #RESTAPI #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
📘 #Day113 of My Java Full Stack Journey Today I learned about the Servlet Life Cycle, which explains how a servlet is created, used, and destroyed by the web container (Tomcat). ✨ 𝐒𝐞𝐫𝐯𝐥𝐞𝐭 𝐋𝐢𝐟𝐞 𝐂𝐲𝐜𝐥𝐞: Servlet life cycle defines the stages a servlet goes through from loading to destruction These stages are managed by the Servlet Container (Tomcat). There are three main life cycle methods: 1️⃣𝐢𝐧𝐢𝐭() This method is called only once when the servlet is loaded for the first time. ➜ It is used to perform initialization tasks like: ▪ Loading configuration ▪ Creating database connections ▪ Allocating resources ➜ Before calling init(), the servlet container first loads the servlet class and creates its object. 𝑬𝒙: public void init() throws ServletException 2️⃣𝐬𝐞𝐫𝐯𝐢𝐜𝐞() This method handles client requests. Each time a request comes from the browser, the service() method is executed. ➜ In HttpServlet, service() internally calls: ▪ doGet() ▪ doPost() based on request type. 𝑬𝒙: public void service(ServletRequest request, ServletResponse response) 3️⃣ 𝐝𝐞𝐬𝐭𝐫𝐨𝐲() This method is called only once when the servlet is removed from memory. ➜ It is used to: ▪ Close database connections ▪ Release resources ▪ Perform cleanup operations 𝑬𝒙: public void destroy() 📌 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 ▪ Servlet life cycle is managed by Tomcat ▪ init() runs only once during initialization ▪ service() handles every client request ▪ destroy() runs before servlet removal Gurugubelli Vijaya Kumar | 10000 Coders #Java #Servlets #ServletLifecycle #ApacheTomcat #JavaWebDevelopment #BackendDevelopment
To view or add a comment, sign in
-
-
Day 1 of 15 -> The Heart of Spring Boot: Beans #SpringBootChallenge | Day 1/15 When I first started with Spring Boot, one word kept appearing: Bean. Phrases like "Register it as a Bean," "Inject the Bean," and "Spring manages the Bean" were everywhere, but I had no idea what it meant, so I ignored it. That was a big mistake. So, what is a Bean? In plain Java, when you need an object, you create it yourself: UserService service = new UserService(); It's simple, but now you are responsible for creating, managing, destroying, and passing it around. In Spring Boot, you delegate that responsibility. You tell Spring, "Hey, manage this object for me." That object is called a Bean. Why is this important? Imagine a large application with 50 classes, all depending on each other. Without Spring, you manually create and wire every object. With Spring, you declare it once, and Spring handles the rest. This is known as Inversion of Control (IoC); you don't control the object lifecycle Spring does. The tool Spring uses to inject these beans where needed is Dependency Injection (DI). The result is: - Less boilerplate code - Loosely coupled components - Easier to test and maintain - One instance shared across the app (by default)
To view or add a comment, sign in
-
🚀 Spring Framework 🌱 | Day 4 Spring Bean Scopes Made Simple (with Real-Life Examples) Understanding bean scopes in Spring is very important for writing efficient applications. Let’s break it down in a simple way 👇 👉 1. Singleton (Default Scope) Only one object is created for the entire application. 🏠 Real-life example: Think of it like a TV in your home – everyone uses the same TV. In Spring, all requests use the same bean instance. 👉 2. Prototype A new object is created every time it is requested. ☕ Real-life example: Ordering coffee at a café – every time you order, you get a new cup. In Spring, each request gets a fresh bean. 👉 3. Request Scope (Web apps only) One object per HTTP request. 🧾 Real-life example: Filling a form online – each request has its own data. Once the request ends, the object is gone. 👉 4. Session Scope One object per user session. 🛒 Real-life example: Shopping cart in an e-commerce app – items stay until you logout or session expires. 💡 Quick Summary: 👉 Singleton → One shared object 👉 Prototype → New object every time 👉 Request → One per HTTP request 👉 Session → One per user session 🚀 Pro Tip: Use the right scope based on your use case to avoid performance and memory issues. #SpringFramework #Java #BackendDevelopment #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 7 — What is Bean? (Core Spring Concept 🔥) Today I understood one important thing… 👉 Everything in Spring is a Bean 💡 What is a Bean? 👉 A Bean is an object created and managed by Spring (IoC container) (Simple: Spring creates object, we just use it) ⚙️ How Spring Creates Bean? Using XML (<bean>) Using Annotations (@Component, @Service) 👉 Spring container creates, manages, and injects beans ⚡ Bean Scope (Important 🔥) 🔹 Singleton (default) 👉 Only ONE object created 🔹 Prototype 👉 New object every time 🔍 Bean Lifecycle (Simple Flow) 👉 Create → Initialize → Use → Destroy 💡 One line I learned: 👉 In Spring, objects are called Beans and Spring manages them 💬 Which scope confused you — Singleton or Prototype? Day 7 done ✅ #Spring #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #SpringBoot #Developers
To view or add a comment, sign in
-
-
New to Spring Boot? You'll see these annotations in every project. Here's what they actually do: @SpringBootApplication → Entry point. Combines @Configuration, @EnableAutoConfiguration, @ComponentScan @RestController → Marks a class as an HTTP request handler that returns data (not views) @Service → Business logic layer. Spring manages it as a bean @Repository → Data access layer. Also enables Spring's exception translation @Autowired → Inject a dependency automatically (prefer constructor injection instead) @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → Maps HTTP methods to your handler methods @RequestBody → Deserializes JSON from request body into a Java object @PathVariable → Extracts values from the URL path Bookmark this. You'll refer back to it constantly. Which annotation confused you the most when starting out? 👇 #Java #SpringBoot #Annotations #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
Understanding @RestController in Spring Boot In Spring Boot, handling client requests is a core part of building applications. @RestController But what does it actually do? @RestController is used to create RESTful web services. It handles incoming HTTP requests and returns responses (usually in JSON format). It is a combination of: @Controller + @ResponseBody This means: ✔ You don’t need to write @ResponseBody on every method ✔ All methods return data directly instead of views Key Responsibilities: 🔹 Handles HTTP requests (GET, POST, PUT, DELETE) 🔹 Maps URLs using annotations like @GetMapping, @PostMapping 🔹 Returns JSON/XML responses In simple terms: @RestController → Takes request → Processes it → Returns response Understanding this annotation is important because it is the entry point for building APIs in Spring Boot. #SpringBoot #Java #BackendDevelopment #LearningInPublic #DeveloperGrowth
To view or add a comment, sign in
-
-
10 Spring Boot annotations — and what they ACTUALLY do. Most developers use these daily but can't explain them. 👇 1. @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan Three annotations in one. This is why your app boots. 2. @RestController = @Controller + @ResponseBody Every method returns data directly. No view templates. 3. @Transactional Wraps your method in a DB transaction. Rolls back on RuntimeException. NOT checked exceptions by default. 4. @Autowired Injects a Spring-managed bean. Constructor injection is preferred. 5. @Value("${property}") Injects values from application.properties/yml at runtime. 6. @Async Makes a method run in a separate thread pool. Useless without @EnableAsync on your config class. 7. @Cacheable Caches the return value. Same input = no method execution. Massive performance win for read-heavy endpoints. 8. @Scheduled Runs a method on a timer/cron. Needs @EnableScheduling — easy to forget. 9. @Profile("prod") Only loads this bean in the specified environment. Lifesaver for environment-specific configs. 10. @ConditionalOnProperty Only creates the bean if a config property exists/matches. The secret weapon for feature flags in Spring Boot. Which one surprised you? And which one have you misused? 👇 Tag a Java dev who needs this cheat sheet. 🚀 #SpringBoot #Java #BackendDevelopment #JavaDeveloper #SoftwareEngineering #Programming #SpringFramework #LearnToCode
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