Configuration, profiles, conditions · Topic 2 of 5
@Configuration and @Bean
Definition​
A @Configuration class contains @Bean methods, and each method describes one bean. It is the way to register objects you do not own (such as a library class) and to wire beans together in plain Java code.
Example code​
Beans that depend on each other, wired in Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
record DatabaseConfig(String url) { }
class OrderRepository {
final DatabaseConfig config;
OrderRepository(DatabaseConfig config) { this.config = config; }
}
@Configuration
class AppConfig {
@Bean
DatabaseConfig databaseConfig() { return new DatabaseConfig("jdbc:h2:mem:shop"); }
@Bean
OrderRepository orderRepository(DatabaseConfig config) { // Spring passes the other bean in
return new OrderRepository(config);
}
}
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println(context.getBean(OrderRepository.class).config.url());
}
}
}
// Output:
// jdbc:h2:mem:shop
Finished this page? Track your progress (saved only in your browser).