0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

O contêiner de IoC do Spring

Entenda como o Spring cria e conecta os beans.

O contêiner de IoC do Spring é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 ApplicationContext manages beans
  • @Component + scanning registers your classes; @Bean handles others
  • Injection resolves by type, disambiguated with @Primary/@Qualifier

Perguntas Frequentes

A aula “O contêiner de IoC do Spring” é grátis?

Sim — o texto completo de “O contêiner de IoC do Spring” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

O que vou aprender em “O contêiner de IoC do Spring”?

Entenda como o Spring cria e conecta os beans. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?

Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “O contêiner de IoC do Spring”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?

Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. O contêiner de IoC do Spring
  2. Injeção por construtor versus por campo
  3. Escopos de beans
  4. Retornos de chamada do ciclo de vida
← Voltar para Spring Boot 4 Microservices & REST APIs