0
0
SpringbootConceptBeginner · 3 min read

@Configuration in Spring: What It Is and How It Works

In Spring, @Configuration is an annotation that marks a class as a source of bean definitions. It tells Spring to treat the class as a configuration file where you can define beans using methods annotated with @Bean.
⚙️

How It Works

Think of @Configuration as a special label you put on a class to tell Spring, "This class contains instructions on how to create and configure objects (beans) that your app needs." When Spring starts, it looks for these classes and runs the methods inside them to create and manage those objects.

This is like a recipe book: each method with @Bean is a recipe for making a specific ingredient (bean). Spring reads the recipes and prepares the ingredients before your app uses them. This helps keep your app organized and makes it easy to change how objects are created without changing the main code.

đź’»

Example

This example shows a simple Spring configuration class that creates a bean for a GreetingService. Spring will manage this bean and provide it wherever needed.

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public GreetingService greetingService() {
        return new GreetingService();
    }
}

class GreetingService {
    public String greet() {
        return "Hello, Spring!";
    }
}
🎯

When to Use

Use @Configuration when you want to define beans in Java code instead of XML files. It is helpful for setting up your application's components, services, or utilities in a clear and type-safe way.

For example, if your app needs a service that connects to a database or sends emails, you can create those beans inside a @Configuration class. This makes your setup easy to manage, test, and change as your app grows.

âś…

Key Points

  • @Configuration marks a class as a source of bean definitions.
  • Methods annotated with @Bean inside this class create and configure beans.
  • Spring processes these classes at startup to manage application components.
  • It replaces XML configuration with clean, type-safe Java code.
âś…

Key Takeaways

@Configuration classes tell Spring how to create and manage beans.
Use @Bean methods inside @Configuration to define objects your app needs.
It replaces XML configs with easy-to-read Java code.
Spring processes these classes at startup to prepare your app’s components.