@Configuration and @Bean help you tell Spring how to create and manage objects your app needs. This makes your app organized and easy to change.
0
0
@Configuration and @Bean in Spring Boot
Introduction
When you want to create and manage your own objects (beans) in Spring.
When you need to configure objects with special settings before using them.
When you want Spring to automatically provide objects to other parts of your app.
When you want to replace or customize default Spring beans with your own versions.
Syntax
Spring Boot
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }
@Configuration marks a class as a source of bean definitions.
@Bean marks a method that returns an object Spring will manage.
Examples
This example creates a simple String bean named 'greeting'.
Spring Boot
@Configuration public class AppConfig { @Bean public String greeting() { return "Hello, Spring!"; } }
This example shows a bean with a constructor argument for custom setup.
Spring Boot
@Configuration public class AppConfig { @Bean public Service service() { return new Service("custom config"); } }
Sample Program
This example shows a configuration class that creates a MessageService bean. Spring will manage this bean and provide it when needed.
Spring Boot
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @Configuration public class AppConfig { @Bean public MessageService messageService() { return new MessageService(); } } class MessageService { public String getMessage() { return "Hello from MessageService!"; } } // In a Spring Boot app, you can get the bean like this: // ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // MessageService service = context.getBean(MessageService.class); // System.out.println(service.getMessage());
OutputSuccess
Important Notes
Each @Bean method creates one object managed by Spring.
@Configuration classes are like blueprints for your app's objects.
Spring automatically calls these methods and keeps the objects ready to use.
Summary
@Configuration marks a class as a place to define beans.
@Bean marks methods that create objects Spring manages.
This helps keep your app organized and flexible.