Junior — Middle
How can you declare a component or bean object in Spring?
sobes.tech AI
Answer from AI
In Spring, components or beans can be declared in several ways:
-
Annotations:
@Component— the basic annotation for automatic component detection.- Specialized annotations that extend
@Component:@Service— for the service layer.@Repository— for the data access layer.@Controller— for MVC controllers.
-
Configuration classes with the
@Configurationannotation:- Inside such classes, you can declare methods with the
@Beanannotation that return bean instances.
- Inside such classes, you can declare methods with the
Example using @Bean:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
Thus, Spring allows declaring beans either through annotated classes and components or through configuration methods.