0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

Injeção por construtor versus por campo

Escolha o estilo de injeção adequado.

Injeção por construtor versus por campo é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 2 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.

Three Ways to Inject

Spring can inject dependencies three ways: through the constructor, into fields, or via setters. They all work, but they are not equal in quality.

The Spring team and community strongly recommend constructor injection. This lesson explains why.

Field Injection

Field injection places @Autowired directly on a field. It looks compact, but hides the dependency and complicates testing.

@Service
public class OrderService {
    @Autowired
    private OrderRepository repo;
    @Autowired
    private PricingService pricing;
}

Constructor Injection

Constructor injection declares dependencies as constructor parameters. Spring supplies them when building the bean. Fields can be final, signaling true immutability.

@Service
public class OrderService {
    private final OrderRepository repo;
    private final PricingService pricing;
    public OrderService(OrderRepository repo, PricingService pricing) {
        this.repo = repo;
        this.pricing = pricing;
    }
}

No @Autowired Needed

Since Spring 4.3, if a bean has a single constructor, @Autowired is optional. This keeps constructor-injected classes clean and annotation-light.

@Service
public class OrderService {
    private final OrderRepository repo;
    // single constructor: no @Autowired required
    public OrderService(OrderRepository repo) {
        this.repo = repo;
    }
}

Immutability and final

Constructor injection lets every dependency be final. The object is fully initialized once and never changes its collaborators, which prevents accidental reassignment and aids thread safety.

Field injection cannot use final, so the object can exist in a partially built state.

Testability Without Spring

A constructor makes dependencies explicit, so unit tests can build the object directly with mocks — no Spring context, no reflection.

@Test
void placesOrder() {
    OrderRepository repo = mock(OrderRepository.class);
    PricingService pricing = mock(PricingService.class);
    OrderService svc = new OrderService(repo, pricing);
    // ... arrange and assert
}

Detecting Too Many Dependencies

A bloated constructor is a visible code smell. If a class needs eight collaborators, the long parameter list screams that it does too much. Field injection hides this and lets god-classes grow unnoticed.

Avoiding Circular Dependencies

Constructor injection surfaces circular dependencies at startup with a clear error, because two beans cannot both be constructed first. Field injection can mask the cycle until runtime, leading to subtle bugs.

A startup failure is the right time to discover and fix a design cycle.

Setter Injection

Setter injection suits genuinely optional dependencies that can change after construction. It is rarely needed; prefer constructor injection for required collaborators.

@Service
public class ReportService {
    private Formatter formatter = new PlainFormatter();
    @Autowired(required = false)
    public void setFormatter(Formatter formatter) {
        this.formatter = formatter;
    }
}

Less Boilerplate with Lombok

If constructors feel verbose, Lombok’s @RequiredArgsConstructor generates one from all final fields, giving constructor injection’s benefits with minimal code.

@Service
@RequiredArgsConstructor
public class OrderService {
    private final OrderRepository repo;
    private final PricingService pricing;
}

Why the Recommendation Stands

Constructor injection wins on every axis:

  • Immutable, fully initialized objects
  • Trivial unit testing without a container
  • Cycles and over-dependency become visible
  • No reflection-only access for tests

Quick Check

Test your understanding of injection styles.

Recap

Prefer constructor injection.

  • Enables final, immutable dependencies
  • Single constructor needs no @Autowired
  • Unit-testable without the Spring context
  • Exposes circular dependencies and over-large classes
  • Use setters only for optional, mutable collaborators

Perguntas Frequentes

A aula “Injeção por construtor versus por campo” é grátis?

Sim — o texto completo de “Injeção por construtor versus por campo” é 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 “Injeção por construtor versus por campo”?

Escolha o estilo de injeção adequado. 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 2 de 4.

Quanto tempo leva a aula “Injeção por construtor versus por campo”?

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