コンストラクターインジェクションとフィールドインジェクション
適切なインジェクション方式を選びます
「コンストラクターインジェクションとフィールドインジェクション」はCoddyKit上の無料Spring Boot 4 Microservices & REST APIsレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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
よくある質問
「コンストラクターインジェクションとフィールドインジェクション」レッスンは無料ですか?
はい。「コンストラクターインジェクションとフィールドインジェクション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Microservices & REST APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。
「コンストラクターインジェクションとフィールドインジェクション」で何を学びますか?
適切なインジェクション方式を選びます ブラウザで直接実行するハンズオンコードでSpring Boot 4 Microservices & REST APIsを演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Spring IoCコンテナ
- コンストラクターインジェクションとフィールドインジェクション
- Beanスコープ
- ライフサイクルコールバック