Junior — Middle
Do you use the @Bean annotation to declare a component in configuration?
sobes.tech AI
Answer from AI
Yes, the @Bean annotation in Spring is used to declare a component (bean) in a configuration class. It explicitly indicates that the method returns an object that should be registered in the Spring context as a bean.
Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
In this example, the myService() method creates and returns an object that Spring registers as a bean named myService. This approach is useful for explicit bean management and configuration.