Junior — Middle
In which cases is it preferable to use the @Configuration annotation in Spring?
sobes.tech AI
Answer from AI
The @Configuration annotation in Spring is used to denote a class that contains bean definitions and application configuration. It is preferable to use @Configuration in the following cases:
- When you need to explicitly define and configure beans using methods annotated with
@Bean. - For creating configuration classes that replace XML configuration.
- If you need to utilize Spring features such as creating proxies for
@Beanmethods (to ensure singleton beans and dependency management).
Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
Thus, @Configuration is convenient for centralized and type-safe description of Spring application configuration.