0Pricing
Spring Boot 4 Microservices & REST APIs · 课时

构造函数注入与字段注入

选择合适的注入方式

构造函数注入与字段注入 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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

常见问题解答

「构造函数注入与字段注入」课时是免费的吗?

是的 — 「构造函数注入与字段注入」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 4 节课。

「构造函数注入与字段注入」这节课中我会学到什么?

选择合适的注入方式 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「构造函数注入与字段注入」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Boot 4 Microservices & REST APIs 课中编写并运行代码吗?

能。每节 Spring Boot 4 Microservices & REST APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Spring IoC 容器
  2. 构造函数注入与字段注入
  3. Bean 作用域
  4. 生命周期回调
← 返回 Spring Boot 4 Microservices & REST APIs