@Configuration and @Bean are Spring annotations used for Java-based configuration. They allow developers to define and manage Spring Beans without using XML configuration files.
Key Points: • @Configuration marks a class as a source of bean definitions for the Spring IoC container. • Spring scans a @Configuration class and processes all methods annotated with @Bean. • @Bean is applied to a method to indicate that the returned object should be managed as a Spring Bean. • Beans created using @Bean are registered in the Spring container and can be injected into other components. • Java-based configuration provides better type safety, readability, and maintainability compared to XML configuration.
Example: A configuration class can define a DataSource or Service object using @Bean, and Spring will automatically create and manage that object throughout the application lifecycle.
Code Example:
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}Interview Tip: A concise interview answer is:
"@Configuration marks a class as a Spring configuration class, while @Bean is used to define objects that should be managed by the Spring IoC container. Spring creates and manages these beans and makes them available for dependency injection."