r/SpringBoot • u/Few-Tower50 • Dec 13 '25
Question How Constructor Injection Works
If possible, can you explain deeply how constructor injection works behind the scenes what exactly happens internally when the dependencies are created and injected and for what reasons constructor injection is generally preferred over field injection?
15
u/ashdgjklashgjkdsahkj Dec 13 '25 edited 4d ago
The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.
Spectacular growth coordinated placid cause lantern
2
7
u/PmMeCuteDogsThanks Dec 13 '25
What research, if any, did you do before this effortless post?
→ More replies (1)
11
3
u/rbygrave Dec 13 '25
Generally preferred over field injection
Tests stay in line as dependencies change
That is, when we change the constructor, then tests using that constructor must be revised and this is a good thing. Tests using the old constructor now don't compile, this forces us to review and update those tests.
2. Helps identify when a component has too many dependencies.
When we see a constructor with say 19 parameters it pretty clearly looks like a code smell. This component has way too many dependencies and therefore is probably doing way too much and needed to be decomposed.
When we use field injection, the "too many dependencies" case isn't as obvious.
3. We desire the dependencies to be final fields / We are looking at DI as approximately "function composition" and desire an "Immutable graph of functions/business logic"
Component and it's stereotypes Controller, Service, Repository are Singleton scope by default. This means they need to be safe for multi-threaded use, aka ideally stateless. So we want the dependencies to be final fields [and the dependencies to also be ideally stateless] (so this is a bit of a FP view of it in terms of separation of "functions" and "data").
Alternatively, this can be viewed as what we generally DO NOT use DI for is to "wire a graph of DATA". That is, a Component should be used for "Business logic/Functions" and not "Data" ... and we want those functions to ideally be Immutable and stateless.
3
u/Nok1a_ Dec 13 '25
I woudl suggest you to read Spring Start here, you have examples on DI in Java and in Spring
1
u/SuspiciousDepth5924 Dec 13 '25
I don't know if this is the reason it's "generally preferred", but on a personal level I find it makes the components much less awkward to test. Especially if compared with @Autowired fields without setters (doubly so if they are also protected/private). It also allows the fields to be final (which is a separate topic, but I tend to think is generally a good thing).
@Component
public class FooWithFieldInject {
@Autowired
Wigdet bar;
@Autowired
private Widget baz;
}
@Component
public class FooWithConstructorInject {
private final Widget bar;
private final Widget baz;
@Autowired
public FooWithConstructorInject(Widget bar, Widget baz) {
this.bar = bar;
this.baz = baz;
}
}
// in some test
var fieldInject = new FooWithFieldInject();
// has to set these separately, compiler won't let you know if you forgot any of them
fieldInject.bar = someTestImplementation();
// Won't work unless you do some dirty reflection stuff
fieldInject.baz = someTestImplementation();
var constructorInject = new FooWithConstructorInject(
someTestImplementation(),
someTestImplementation()
);Of course you could test the field version with \@SpringBootTest or something similar so that spring handles the fields for you, but then you have to load up an entire spring context which makes the test significantly heavier when you otherwise could just have a regular unit test.
1
1
u/ShoulderPast2433 Dec 15 '25
Which exact aspect of constructor DI vs field DI do you have problem understanding?
1
u/Difficult-Task6751 Dec 16 '25
Can someone explain me how constructor injection avoids circular dependencies?
1
u/KlassyCoder Dec 16 '25
No one here has mentioned the security aspect of constructor vs field injection.
Field injection requires mutable variables, while constructor injection lets us make them immutable with final. Mutable variables can be maliciously overwritten for nefarious purposes.
If you're not the only one working in your codebase, and your files are exceedingly large or complex, it's not difficult for someone to instantiate and obfuscate a malicious version of the injected class and overwrite the Spring-injected version without you noticing. Code reviews etc should catch things like this, but we should close as many attack vectors as possible as a standard practice.
I wrote a short piece on this earlier this year that provides a very basic example.
64
u/innocentVince Dec 13 '25
Well, on the high level it's just "java.lang.reflect" (so reflection)
What it does is, on application startup it loads all compiled .class files. Then it goes over all the class files, creates a list of all beans that are annotated with a dependency injection annotation from Spring (@Service, @Component, ...).
Then before your actual application starts, from the reflect package it builds the classes as objects (and this recursively for all dependencies of dependencies) and stores it in an internal Spring Context. Now Spring handles these classes as "beans" / Spring manages the lifecycle of the object now (Singletons).
Same for field injection. For constructor injection, it checks the params of the constructor.