Bird
Raised Fist0
Spring Bootframework~15 mins

@Configuration and @Bean in Spring Boot - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the @Configuration annotation in Spring Boot?
easy
A. To enable automatic component scanning
B. To mark a method that returns a bean instance
C. To mark a class as a source of bean definitions for the application context
D. To configure database connections automatically

Solution

  1. Step 1: Understand the role of @Configuration

    @Configuration tells Spring that this class contains methods to create beans.
  2. Step 2: Differentiate from other annotations

    @Bean marks methods, not classes; component scanning is done by @ComponentScan; database config is separate.
  3. Final Answer:

    To mark a class as a source of bean definitions for the application context -> Option C
  4. Quick Check:

    @Configuration = class for beans [OK]
Hint: Remember: @Configuration is for classes, @Bean is for methods [OK]
Common Mistakes:
  • Confusing @Configuration with @Bean
  • Thinking @Configuration enables scanning
  • Assuming it configures databases automatically
2. Which of the following is the correct way to define a bean method inside a @Configuration class?
easy
A. @Bean public MyBean myBean() { return new MyBean(); }
B. @Configuration public MyBean myBean() { return new MyBean(); }
C. public void createBean() { return new MyBean(); }
D. @Component public MyBean myBean() { return new MyBean(); }

Solution

  1. Step 1: Check method signature for bean creation

    Bean methods must be annotated with @Bean and return the bean object.
  2. Step 2: Verify syntax correctness

    @Bean public MyBean myBean() { return new MyBean(); } correctly uses @Bean and returns a new instance.
  3. Final Answer:

    @Bean public MyBean myBean() { return new MyBean(); } -> Option A
  4. Quick Check:

    @Bean + return bean instance = correct method [OK]
Hint: Bean methods need @Bean and must return the object [OK]
Common Mistakes:
  • Missing @Bean annotation
  • Using void return type
  • Using @Configuration on methods
3. Given the following code, what will be the output when retrieving the bean named "service" from the Spring context?
@Configuration
public class AppConfig {
  @Bean
  public String service() {
    return "MyService";
  }
}
medium
A. "service"
B. "MyService"
C. An exception is thrown
D. null

Solution

  1. Step 1: Identify the bean method and its return value

    The method named service returns the string "MyService" and is annotated with @Bean.
  2. Step 2: Understand bean retrieval by name

    Spring registers this bean with the name "service" and returns the method's return value when requested.
  3. Final Answer:

    "MyService" -> Option B
  4. Quick Check:

    Bean name returns method's return value [OK]
Hint: Bean name matches method name; returns method's return value [OK]
Common Mistakes:
  • Expecting bean name as output instead of return value
  • Thinking Spring returns null if no explicit name
  • Assuming exception without error in code
4. Identify the error in the following Spring configuration code:
@Configuration
public class Config {
  @Bean
  public void createBean() {
    // no return statement
  }
}
medium
A. Method must return an object, not void
B. Missing @Configuration annotation
C. Method name cannot be createBean
D. No error, code is correct

Solution

  1. Step 1: Check method return type for @Bean

    Bean methods must return the bean object; void return type is invalid.
  2. Step 2: Confirm annotations and method name

    @Configuration is present; method name can be anything; error is only return type.
  3. Final Answer:

    Method must return an object, not void -> Option A
  4. Quick Check:

    @Bean method needs return value, not void [OK]
Hint: Bean methods must return an object, never void [OK]
Common Mistakes:
  • Using void return type for @Bean methods
  • Confusing method name restrictions
  • Missing @Configuration annotation (not in this case)
5. You want to create two beans of the same type but with different configurations using @Bean methods inside a @Configuration class. How can you ensure Spring distinguishes between them when injecting?
hard
A. Define both beans in separate @Configuration classes only
B. Use @Primary on both methods
C. Use the same method name but different return types
D. Use different method names for each @Bean method

Solution

  1. Step 1: Understand bean naming in Spring

    By default, Spring uses the @Bean method name as the bean name to distinguish beans.
  2. Step 2: Differentiate beans of same type

    Using different method names creates distinct bean names, allowing injection by name or qualifier.
  3. Final Answer:

    Use different method names for each @Bean method -> Option D
  4. Quick Check:

    Different method names = different bean names [OK]
Hint: Different method names create distinct bean names automatically [OK]
Common Mistakes:
  • Using @Primary on both beans (conflicts)
  • Same method name with different return types (not allowed)
  • Thinking beans must be in separate classes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard