Spring Boot Annotations: @Configuration and @Bean Explained

🚀 Day 7/100: Spring Boot From Zero to Production Topic: @Configuration and @Bean Building on what we discussed yesterday, we can’t really call ourselves Spring Boot developers until we truly get a grip on Annotations. They are the heart of how this framework functions. Today, we’re looking at two heavy hitters: @Configuration and @Bean. -> What’s the deal with Custom Configuration? In a ideal world, Spring Boot’s "Auto-configuration" handles everything. But in the real world, we often need to override the defaults or provide our own custom setup. While we do a lot of this in application.yaml or application.properties files, there are scenarios where we need the power of Java code to define our components. 1. @Configuration: The Blueprint This is a class-level annotation. When you mark a class with @Configuration, you’re telling Spring: "Hey, this is a configuration component. Look inside for bean definitions!" The Role: It flags the class as a source of beans. The Scan: Because it’s a specialized version of @Component, the @ComponentScan we talked about yesterday will find it automatically. 2. @Bean: The Object Factory Methods inside a @Configuration class are usually annotated with @Bean. These methods return an object (like a library client, a security filter, or a data source). The Container: Spring executes the method, takes the object it returns, and registers it in the Spring Container. The Benefit: Once it’s in the container, Spring manages its entire lifecycle making it ready for Dependency Injection anywhere else in your app. 💡 The "Hidden" Singleton Pattern Here’s a cool technical detail: this is actually a clever implementation of the Singleton Pattern. By default, when one @Bean method calls another @Bean method within the same @Configuration class, Spring intercepts that call. Instead of running the method again and creating a new instance, it simply pulls the existing instance from the container. Working with Spring Boot, you are going to see @Configuration and @Bean everywhere. They are the bread and butter of a flexible backend! Below is an example attached from one of my demo projects. If you have any questions about how these work or when to use them over properties files, just leave a comment and I’ll be happy to address it. 👋 See you in the next post! 🚀 #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend

  • text

To view or add a comment, sign in

Explore content categories