@Configuration and @Bean: Programmatic Wiring
@Configuration and @Bean: Programmatic Wiring
Not everything fits component scanning, and that is what @Configuration classes are for. They are plain Java classes with methods that create beans, giving you full control over wiring while staying type-safe and refactorable. This style is sometimes called Java-based configuration.
Defining a configuration class
Annotate a class with @Configuration. Each method annotated with @Bean returns an object that the container registers as a bean. The method name becomes the bean name by default, and configuration classes are themselves processed by the container, so they can inject other beans.
@Configuration
public class AppConfig {
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.url("jdbc:h2:mem:app")
.build();
}
}
When to use it
Prefer @Bean when you create the object with your own construction logic: third-party libraries, conditional recipes that depend on configuration values, or objects needing explicit setup. For your own classes that Spring can discover, stereotype annotations plus constructor injection are simpler.
Inter-bean references
A @Bean method can call another @Bean method in the same class. Because configuration classes are proxied, these calls request a bean from the container, so the same singleton instance is reused and proxying still applies. This reads naturally while preserving the container.
Conditional wiring
Combine @Bean with @Profile to switch beans based on environment. That is exactly how Boot's own auto-configuration offers sensible defaults you can override with a single bean of your own.
Key Points
@Configurationclasses define beans with@Beanmethods.- Method names become bean names; return types are the bean types.
- Use
@Beanfor third-party or programmatically built objects. - Inter-bean calls within a configuration go through the container.
- Combine with profiles for environment-aware wiring.