Junior — Middle
At what level should components be declared using the @Bean annotation in Spring?
sobes.tech AI
Answer from AI
In Spring, components with the @Bean annotation are declared at the method level inside a class marked as a configuration class (usually annotated with @Configuration).
That is, @Bean is placed above a method that returns an object of a component (bean), and the class itself acts as a container for such methods. This allows Spring to create and manage the lifecycle of these beans.
Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
Thus, @Bean is not placed on the class or field, but specifically on methods inside a configuration class.