El contenedor IoC de Spring
Descubra cómo Spring crea y conecta los beans
El contenedor IoC de Spring es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Inversion of Control
Inversion of Control (IoC) means your objects no longer create their own collaborators. Instead, a container constructs them and hands over (injects) their dependencies.
This flips the traditional flow: rather than calling new everywhere, you declare what you need and let the framework wire it up.
The ApplicationContext
Spring’s IoC container is the ApplicationContext. It reads bean definitions, instantiates them, resolves dependencies, and manages their lifecycle from creation to shutdown.
In Spring Boot, SpringApplication.run builds this context for you and keeps it running.
What Is a Bean?
A bean is simply an object that the container creates and manages. The context knows how to build it, what it depends on, and when to destroy it.
Beans are typically singletons living for the life of the application, though other scopes exist.
Declaring Beans with @Component
Annotate a class with @Component and component scanning will register it. Specializations like @Service, @Repository, and @Controller are @Component with added semantics.
@Service
public class OrderService {
public void placeOrder() { /* ... */ }
}
@Repository
public class OrderRepository { }Component Scanning
@SpringBootApplication includes @ComponentScan, which searches the main class’s package and sub-packages for stereotype annotations. Keep your classes under that root package so they are discovered.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Declaring Beans with @Bean
For types you do not own or want to configure manually, define a factory method annotated @Bean inside a @Configuration class. The return value becomes a managed bean.
@Configuration
public class AppConfig {
@Bean
public RestClient restClient() {
return RestClient.builder()
.baseUrl("https://api.example.com")
.build();
}
}@Component vs @Bean
Both create beans, but differ in control:
@Component— you own the class and let scanning register it@Bean— explicit factory method, ideal for third-party classes or conditional construction
Dependency Injection in Action
The container reads a bean’s constructor parameters and supplies matching beans. Here OrderService receives a fully built OrderRepository automatically.
@Service
public class OrderService {
private final OrderRepository repo;
public OrderService(OrderRepository repo) {
this.repo = repo;
}
}Resolving by Type
Spring injects by type. If exactly one bean matches the parameter type, it is wired in. The bean’s concrete class can implement an interface, and you inject the interface.
@Service
public class NotificationService {
private final MessageSender sender; // interface
public NotificationService(MessageSender sender) {
this.sender = sender; // gets the single impl bean
}
}Handling Multiple Candidates
When several beans match a type, disambiguate with @Primary on the default, or @Qualifier at the injection point to name the exact one.
@Bean @Primary
MessageSender emailSender() { return new EmailSender(); }
@Bean
MessageSender smsSender() { return new SmsSender(); }
// inject a specific one
public Svc(@Qualifier("smsSender") MessageSender s) { }Why IoC Helps
Delegating wiring to the container brings real benefits:
- Testability — inject mocks instead of real collaborators
- Loose coupling — depend on interfaces, not constructors
- Centralized lifecycle — one place manages creation and shutdown
Quick Check
Test your understanding of bean declaration.
Recap
The IoC container wires your application together.
- IoC means the container, not your code, creates and injects collaborators
- The
ApplicationContextmanages beans @Component+ scanning registers your classes;@Beanhandles others- Injection resolves by type, disambiguated with
@Primary/@Qualifier
Preguntas frecuentes
¿La lección «El contenedor IoC de Spring» es gratis?
Sí — el texto completo de «El contenedor IoC de Spring» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
¿Qué aprenderé en «El contenedor IoC de Spring»?
Descubra cómo Spring crea y conecta los beans Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?
No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «El contenedor IoC de Spring»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?
Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- El contenedor IoC de Spring
- Inyección por constructor frente a inyección por campos
- Ámbitos de los beans
- Callbacks del ciclo de vida