Le conteneur IoC de Spring
Découvrez comment Spring crée et relie les beans.
Le conteneur IoC de Spring est une leçon Spring Boot 4 Microservices & REST APIs gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Boot 4 Microservices & REST APIs, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Boot 4 Microservices & REST APIs comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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
Questions Fréquemment Posées
La leçon « Le conteneur IoC de Spring » est-elle gratuite ?
Oui — le texte complet de « Le conteneur IoC de Spring » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Boot 4 Microservices & REST APIs, passe à CoddyKit PRO. Le cours Spring Boot 4 Microservices & REST APIs comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Le conteneur IoC de Spring » ?
Découvrez comment Spring crée et relie les beans. Tu pratiques Spring Boot 4 Microservices & REST APIs avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Spring Boot 4 Microservices & REST APIs ?
Aucune expérience préalable n'est requise. Spring Boot 4 Microservices & REST APIs sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.
Combien de temps prend la leçon « Le conteneur IoC de Spring » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Spring Boot 4 Microservices & REST APIs ?
Oui. Chaque leçon Spring Boot 4 Microservices & REST APIs inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Le conteneur IoC de Spring
- Injection par constructeur ou par champ
- Portées des beans
- Rappels du cycle de vie