0Pricing
Spring Boot 4 Microservices & REST APIs · Lekcja

Wstrzykiwanie przez konstruktor a przez pole

Wybierz właściwy styl wstrzykiwania

Wstrzykiwanie przez konstruktor a przez pole to bezpłatna lekcja Spring Boot 4 Microservices & REST APIs na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Microservices & REST APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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

Często zadawane pytania

Czy lekcja „Wstrzykiwanie przez konstruktor a przez pole” jest bezpłatna?

Tak — pełny tekst „Wstrzykiwanie przez konstruktor a przez pole” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Microservices & REST APIs, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Co nauczysz się w „Wstrzykiwanie przez konstruktor a przez pole”?

Wybierz właściwy styl wstrzykiwania Ćwiczysz Spring Boot 4 Microservices & REST APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Microservices & REST APIs?

Nie wymagamy żadnego doświadczenia. Spring Boot 4 Microservices & REST APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Wstrzykiwanie przez konstruktor a przez pole”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Microservices & REST APIs?

Tak. Każda lekcja Spring Boot 4 Microservices & REST APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Kontener IoC Spring
  2. Wstrzykiwanie przez konstruktor a przez pole
  3. Zakresy beanów
  4. Wywołania zwrotne cyklu życia
← Powrót do Spring Boot 4 Microservices & REST APIs