Junior — Middle
How is class registration in the Spring container for dependency injection performed?
sobes.tech AI
Answer from AI
In Spring, class registration in the container for dependency injection is usually done using annotations. The main methods:
- The
@Componentannotation (and its specialized variants@Service,@Repository,@Controller) on a class — Spring will automatically detect such a class during package scanning (component scanning) and register it as a bean. - Using a configuration class with the
@Configurationannotation and a method annotated with@Bean, which returns an instance of the required class.
Example with @Component:
@Component
public class MyService {
// service logic
}
Example with @Bean:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
Thus, the Spring container manages the lifecycle of these objects and injects them where needed through autowiring (@Autowired).