0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

Внедрение через конструктор и поле

Выберите подходящий способ внедрения зависимостей

«Внедрение через конструктор и поле» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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

Часто задаваемые вопросы

Урок «Внедрение через конструктор и поле» бесплатный?

Да — полный текст урока «Внедрение через конструктор и поле» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «Внедрение через конструктор и поле»?

Выберите подходящий способ внедрения зависимостей Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Внедрение через конструктор и поле»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Контейнер Spring IoC
  2. Внедрение через конструктор и поле
  3. Области видимости бинов
  4. Обратные вызовы жизненного цикла
← Назад к Spring Boot 4 Microservices & REST APIs