0
0
Spring Bootframework~15 mins

@Configuration and @Bean in Spring Boot - Deep Dive

Choose your learning style9 modes available
Overview - @Configuration and @Bean
What is it?
@Configuration and @Bean are annotations in Spring Boot used to define and manage objects called beans. @Configuration marks a class as a source of bean definitions. @Bean marks methods inside that class to create and return beans that Spring manages. This helps organize and control how parts of your application are created and connected.
Why it matters
Without @Configuration and @Bean, managing how objects are created and linked would be manual and error-prone, especially as applications grow. These annotations let Spring automatically handle object creation and sharing, making code cleaner and easier to maintain. Without them, developers would spend more time writing boilerplate code and fixing bugs related to object management.
Where it fits
Before learning these, you should understand basic Java classes and objects and the idea of dependency injection. After mastering @Configuration and @Bean, you can explore more advanced Spring features like component scanning, profiles, and conditional beans.
Mental Model
Core Idea
@Configuration classes tell Spring how to make beans, and @Bean methods create those beans for Spring to manage and share.
Think of it like...
Think of @Configuration as a recipe book and @Bean methods as individual recipes. The recipe book organizes how to make dishes, and each recipe tells you exactly how to prepare one dish. Spring follows the book to cook and serve dishes (beans) whenever needed.
┌─────────────────────┐
│  @Configuration     │
│  (Recipe Book)      │
│                     │
│  ┌───────────────┐  │
│  │ @Bean Method  │  │
│  │ (Recipe)      │  │
│  └───────────────┘  │
└─────────┬───────────┘
          │
          ▼
   Spring creates and manages
          beans (dishes)
Build-Up - 7 Steps
1
FoundationWhat is a Spring Bean?
🤔
Concept: Introduce the idea of a bean as a managed object in Spring.
In Spring, a bean is an object that Spring creates, configures, and manages for you. Instead of creating objects manually with 'new', Spring can create and share these beans across your app. Beans help organize your code and make it easier to change or test.
Result
You understand that beans are objects Spring controls to help your app work smoothly.
Understanding beans is key because Spring’s power comes from managing these objects for you.
2
FoundationWhat Does @Configuration Do?
🤔
Concept: @Configuration marks a class as a place where Spring looks for bean definitions.
When you add @Configuration to a class, you tell Spring: 'Look here for instructions on how to create beans.' This class acts like a blueprint or recipe book for Spring to follow when building your app’s objects.
Result
Spring knows to scan this class for bean creation methods.
Knowing @Configuration helps you organize bean creation in one place, making your app easier to manage.
3
IntermediateHow @Bean Methods Work
🤔Before reading on: do you think @Bean methods are called once or every time you need the object? Commit to your answer.
Concept: @Bean marks methods inside @Configuration classes that create and return beans.
Inside a @Configuration class, you write methods annotated with @Bean. Each method creates and returns an object. Spring calls these methods to get the bean and then manages that object’s lifecycle. By default, Spring calls each @Bean method once and reuses the same object.
Result
Spring creates one instance per @Bean method and shares it wherever needed.
Understanding that @Bean methods produce shared single instances explains how Spring avoids creating duplicate objects.
4
IntermediateBean Lifecycle and Scope Basics
🤔Before reading on: do you think all beans live forever or can they have different lifetimes? Commit to your answer.
Concept: Beans have lifecycles and scopes that control how long they live and how many instances exist.
By default, beans are singletons, meaning Spring creates one instance and shares it. But you can change this to create new instances each time or limit their lifetime. This controls resource use and behavior in your app.
Result
You can control bean sharing and lifetime to fit your app’s needs.
Knowing bean scopes helps you design efficient and correct applications by controlling object reuse.
5
IntermediateDependency Injection with @Bean Methods
🤔Before reading on: do you think @Bean methods can use other beans as inputs? Commit to your answer.
Concept: @Bean methods can accept parameters that Spring fills with other beans, enabling dependency injection.
If a @Bean method has parameters, Spring looks for beans of those types and passes them in. This lets beans depend on each other cleanly without manual wiring. Spring handles the order and creation automatically.
Result
Beans can be connected and depend on each other without extra code.
Understanding this automatic wiring unlocks the power of Spring’s dependency injection system.
6
AdvancedHow @Configuration Enhances @Bean with Proxying
🤔Before reading on: do you think Spring calls @Bean methods directly every time or uses a special trick? Commit to your answer.
Concept: @Configuration classes are enhanced by Spring to ensure @Bean methods return shared instances even when called internally.
Spring creates a special proxy around @Configuration classes. When one @Bean method calls another inside the same class, the proxy intercepts the call and returns the shared bean instead of creating a new one. This prevents duplicate beans and keeps singleton behavior intact.
Result
Your beans remain singletons even if @Bean methods call each other inside the class.
Knowing about proxying explains why @Configuration is needed instead of just @Bean alone for correct singleton behavior.
7
ExpertCommon Pitfalls with @Bean and @Configuration
🤔Before reading on: do you think missing @Configuration on a class with @Bean methods affects bean sharing? Commit to your answer.
Concept: Without @Configuration, @Bean methods behave differently and can create multiple instances, breaking singleton expectations.
If you omit @Configuration and only use @Bean, Spring treats the class as a simple component. It does not create the proxy that manages singleton behavior. As a result, each @Bean method call creates a new instance, causing bugs and unexpected behavior.
Result
You avoid subtle bugs by always using @Configuration with @Bean methods.
Understanding this subtlety prevents hard-to-find bugs in large Spring applications.
Under the Hood
Spring uses a special proxy class to wrap @Configuration classes. This proxy intercepts calls to @Bean methods to ensure that each bean is created only once and then cached. When a @Bean method is called, the proxy checks if the bean already exists in the Spring container. If yes, it returns the cached instance; if no, it calls the method to create the bean and stores it. This mechanism supports singleton scope and dependency injection between beans.
Why designed this way?
This design allows developers to write simple Java methods to define beans while Spring handles complex lifecycle and dependency management behind the scenes. The proxy approach avoids requiring developers to write boilerplate code for caching or wiring beans. Alternatives like manual object creation or XML configuration were more error-prone and less flexible. Proxying @Configuration classes ensures consistent singleton behavior even when beans depend on each other.
┌─────────────────────────────┐
│  @Configuration Class Proxy  │
│                             │
│  ┌───────────────┐          │
│  │ @Bean Method  │◄─────────┤
│  └───────────────┘          │
│         │                   │
│         ▼                   │
│  Check cache for bean       │
│         │                   │
│   ┌─────┴─────┐             │
│   │ Exists?   │             │
│   └─────┬─────┘             │
│         │Yes                │
│         ▼                   │
│  Return cached bean         │
│         │                   │
│         No                  │
│         ▼                   │
│  Call original method       │
│  Create bean instance       │
│  Store in cache             │
│  Return new bean            │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does omitting @Configuration still guarantee singleton beans? Commit to yes or no.
Common Belief:If I put @Bean on methods, Spring will always create singleton beans regardless of @Configuration.
Tap to reveal reality
Reality:Without @Configuration, Spring does not proxy the class, so each @Bean method call creates a new instance, breaking singleton behavior.
Why it matters:This causes multiple instances of supposed singletons, leading to bugs like inconsistent state or resource waste.
Quick: Do @Bean methods run every time you ask for the bean? Commit to yes or no.
Common Belief:@Bean methods are called every time you request the bean, so they create new objects each time.
Tap to reveal reality
Reality:Spring calls @Bean methods once per bean lifecycle and caches the result, returning the same instance on later requests.
Why it matters:Misunderstanding this leads to inefficient code or incorrect assumptions about bean lifetimes.
Quick: Can @Bean methods have parameters that Spring fills automatically? Commit to yes or no.
Common Belief:@Bean methods cannot take parameters; they must create beans without inputs.
Tap to reveal reality
Reality:@Bean methods can have parameters, and Spring injects other beans automatically to satisfy dependencies.
Why it matters:Missing this means you might write more complicated code to manually wire dependencies.
Quick: Does calling one @Bean method from another inside the same class create multiple beans? Commit to yes or no.
Common Belief:Calling a @Bean method from another inside the same class creates a new bean instance each time.
Tap to reveal reality
Reality:With @Configuration proxying, Spring intercepts such calls and returns the shared singleton bean instead of creating a new one.
Why it matters:Not knowing this can cause unexpected multiple instances or bugs when beans depend on each other.
Expert Zone
1
The proxying of @Configuration classes uses CGLIB by default, which subclasses the configuration class at runtime to intercept method calls.
2
Using @Bean methods inside non-@Configuration classes disables proxying, so beans behave like prototypes even if singleton scope is declared.
3
Spring allows customizing bean creation order and dependencies via method parameters and @DependsOn, which can solve complex initialization sequences.
When NOT to use
Avoid using @Configuration and @Bean for simple components that can be auto-detected with @Component and component scanning. For very dynamic or runtime bean creation, consider using BeanFactory or programmatic registration instead.
Production Patterns
In real-world apps, @Configuration classes group related beans logically, often per feature or module. @Bean methods define complex beans needing custom setup. Developers combine @Configuration with profiles to load beans conditionally for different environments.
Connections
Dependency Injection
Builds-on
Understanding @Configuration and @Bean deepens your grasp of dependency injection by showing how Spring creates and manages dependencies behind the scenes.
Factory Design Pattern
Same pattern
The @Bean methods act like factory methods that produce objects, illustrating the factory pattern in a modern framework context.
Recipe Books in Cooking
Opposite pattern
Unlike a static recipe book, @Configuration classes are dynamic and can produce different beans based on runtime conditions, showing flexibility beyond fixed instructions.
Common Pitfalls
#1Forgetting to add @Configuration on a class with @Bean methods.
Wrong approach:public class AppConfig { @Bean public Service service() { return new Service(); } }
Correct approach:@Configuration public class AppConfig { @Bean public Service service() { return new Service(); } }
Root cause:Without @Configuration, Spring does not create a proxy to manage singleton beans, causing multiple instances.
#2Calling one @Bean method directly from another without proxying.
Wrong approach:@Configuration public class AppConfig { @Bean public Repo repo() { return new Repo(); } @Bean public Service service() { return new Service(repo()); // direct call } }
Correct approach:@Configuration public class AppConfig { @Bean public Repo repo() { return new Repo(); } @Bean public Service service(Repo repo) { return new Service(repo); // injected by Spring } }
Root cause:Direct calls bypass Spring proxy, creating new instances instead of reusing beans.
#3Assuming @Bean methods run every time you request a bean.
Wrong approach:public class AppConfig { @Bean public Connection connection() { System.out.println("Creating connection"); return new Connection(); } } // In code Connection c1 = context.getBean(Connection.class); Connection c2 = context.getBean(Connection.class);
Correct approach:Same code, but understand that "Creating connection" prints only once because Spring caches the bean.
Root cause:Misunderstanding Spring’s caching of singleton beans leads to wrong assumptions about bean creation frequency.
Key Takeaways
@Configuration classes are special blueprints that tell Spring how to create and manage beans.
@Bean methods inside these classes produce objects that Spring manages as singletons by default.
Spring uses proxies to ensure that beans are created once and shared, even when @Bean methods call each other.
Missing @Configuration or calling @Bean methods directly can cause multiple instances and bugs.
Understanding these concepts unlocks the power of Spring’s dependency injection and object management.