You are currently viewing Spring Boot @Configuration and @Bean Tutorial

Spring Boot @Configuration and @Bean Tutorial

1. Introduction:

@Configuration and @Bean annotations in Spring Boot provide a way to configure the Spring IoC (Inversion of Control) container. They allow you to define beans explicitly in a Java-based configuration class.

2. Create a Simple Spring Boot Project:

Start by creating a new Spring Boot project using your preferred IDE or Spring Initializr ( Include the “Spring Web” dependency to enable basic web functionality.

3. @Configuration Annotation:

Create a configuration class annotated with @Configuration. This class will contain methods annotated with @Bean to define beans.

4. @Bean Annotation:

Define beans using the @Bean annotation within the AppConfig class. Beans are created by methods annotated with @Bean.

Here, MyBean and AnotherBean are custom classes, and myBean() and anotherBean() methods are annotated with @Bean to indicate that they define beans.

5. Using @Autowired with @Configuration:

You can use @Autowired to inject beans defined in the @Configuration class into other components.

In this example, MyService is annotated with @Service and injects MyBean through constructor injection.

6. Running the Spring Boot Application:

Create a main method in your application class (the one with the @SpringBootApplication annotation) and run the application.

7. Exploring Advanced Configurations:

  • Conditional Bean Creation:
    You can conditionally create beans based on certain conditions. Explore @ConditionalOn... annotations.
  • Bean Initialization and Destruction:
    You can define methods for bean initialization and destruction using @PostConstruct and @PreDestroy annotations.
  • External Configuration:
    Use @Value annotation to inject properties from external configuration files into your beans.

8. Conclusion:

@Configuration and @Bean annotations in Spring Boot provide a powerful and flexible way to configure and create beans. They allow you to centralize your configuration in Java classes, promoting a clean and modular structure for your Spring Boot applications.

As you delve deeper into Spring Boot, you’ll discover more advanced features and configurations. The official Spring Boot documentation ( is an excellent resource for in-depth exploration.

Leave a Reply