Контейнер Spring IoC
Узнайте, как Spring создаёт и связывает бины
«Контейнер Spring IoC» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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
Часто задаваемые вопросы
Урок «Контейнер Spring IoC» бесплатный?
Да — полный текст урока «Контейнер Spring IoC» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.
Чему я научусь в уроке «Контейнер Spring IoC»?
Узнайте, как Spring создаёт и связывает бины Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?
Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Контейнер Spring IoC»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?
Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Контейнер Spring IoC
- Внедрение через конструктор и поле
- Области видимости бинов
- Обратные вызовы жизненного цикла