0Pricing
Spring Boot 4 Microservices & REST APIs · Lezione

Injection tramite costruttore o campo

Scelga lo stile di injection più adatto.

Injection tramite costruttore o campo è una lezione Spring Boot 4 Microservices & REST APIs gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Microservices & REST APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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

Domande Frequenti

La lezione «Injection tramite costruttore o campo» è gratuita?

Sì — il testo completo di «Injection tramite costruttore o campo» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Microservices & REST APIs, passa a CoddyKit PRO. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Cosa imparerò in «Injection tramite costruttore o campo»?

Scelga lo stile di injection più adatto. Eserciti Spring Boot 4 Microservices & REST APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Boot 4 Microservices & REST APIs?

Non è richiesta alcuna esperienza precedente. Spring Boot 4 Microservices & REST APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Injection tramite costruttore o campo»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Microservices & REST APIs?

Sì. Ogni lezione Spring Boot 4 Microservices & REST APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Il container IoC di Spring
  2. Injection tramite costruttore o campo
  3. Scope dei bean
  4. Callback del ciclo di vita
← Torna a Spring Boot 4 Microservices & REST APIs