Sobes.tech
Junior

What annotations do you know that Spring uses to create beans based on these annotations?

sobes.tech AI

Answer from AI

  • @Component - a general annotation for managed components.
  • @Repository - for data access classes (DAO).
  • @Service - for business logic classes.
  • @Controller - for classes representing REST controllers (@RestController is @Controller + @ResponseBody).
  • @Configuration - for classes containing methods annotated with @Bean.
  • @Bean - for creating a bean instance via a method in a @Configuration class.
  • @Scope - defines the scope of a bean (singleton, prototype, request, session, application, websocket).
  • @Lazy - indicates lazy initialization of a bean.
  • @Primary - indicates the preferred bean when multiple candidates of the same type exist.
  • @Qualifier - used with @Autowired to specify a particular bean by name when multiple candidates of the same type exist.
  • @Profile - indicates that a bean should only be created when a specific profile is active.
  • @Value - for injecting values from properties files.
  • @Autowired - for automatic dependency injection (bean wiring).
  • @Required - (deprecated but may still be used) indicates that a property must be set during configuration.

Example of using @Configuration and @Bean:

// src/main/java/com/example/config/AppConfig.java
package com.example.config;

import com.example.service.MyService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration // Indicates a Spring configuration class
public class AppConfig {

    @Bean // Indicates that this method creates a bean
    public MyService myService() {
        return new MyService(); // Creates a bean instance
    }
}

Example of using @Component:

// src/main/java/com/example/component/MyComponent.java
package com.example.component;

import org.springframework.stereotype.Component;

@Component // Indicates a component managed by the Spring container
public class MyComponent {

    // ... component logic
}