Sobes.tech
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:

  1. 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.
  2. Configuration classes with the @Configuration annotation:

    • Inside such classes, you can declare methods with the @Bean annotation that return bean instances.

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.

How can you declare a component or bean object in… - sobes.tech