Quick revision
The short answer
We make both fields private final and add a constructor OrderService(OrderRepository repo, PaymentClient payments) that assigns them; with only one constructor, no @Autowired is needed. Tests can then simply call new OrderService(fakeRepo, mockPayments), without a Spring context and without reflection. Lombok's @RequiredArgsConstructor can generate the same constructor if the team uses Lombok.
What to remember
In this answer, we rewrote OrderService from field injection to constructor injection by making the fields private final and adding one constructor that takes both dependencies; with a single constructor Spring needs no @Autowired. Tests change the most: they call new OrderService(fakeRepo, mockPayments), run without a Spring context or reflection, and stop compiling when a dependency is added. Lombok's @RequiredArgsConstructor can generate the same constructor, with the small cost of hiding it from readers.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We make both fields private final and add a constructor OrderService(OrderRepository repo, PaymentClient payments) that assigns them; with only one constructor, no @Autowired is needed. Tests can then simply call new OrderService(fakeRepo, mockPayments), without a Spring context and without reflection. Lombok's @RequiredArgsConstructor can generate the same constructor if the team uses Lombok.
Why this question is asked
Converting field injection to constructor injection is one of the most common small refactorings in Spring code bases, and interviewers like it as a coding question because it is short enough to write live and still shows whether we understand the reasons behind the change. In this answer, we will start from the given class, show what testing it looks like today, rewrite it step by step, then rewrite the test, look at the Lombok shortcut, and finish with a few details that are easy to get wrong.
1The Starting Point
Here is the class from the question, with a method added so that we have something to test. Spring creates it with the implicit no-argument constructor and then writes the two dependencies into the fields with reflection, Java's ability to set fields at runtime even when we cannot reach them from code.
Notice that the fields are package-private and mutable. Any code in the package can replace them, and nothing in the class signature tells a reader that OrderService needs a repository and a payment client.
2Testing It Today
To unit test this class without starting Spring, we have to get fakes into those fields somehow.
Each of these options works, and each has a weakness. Setting the fields directly couples the test to the field names and the package. Reflection breaks silently when a field is renamed. @InjectMocks quietly leaves a new dependency null when someone adds one, so the test fails later with a NullPointerException instead of telling us what is missing.
3The Rewrite
Now we rewrite the class. The steps are small: make the fields private and final, add a constructor that takes both dependencies, and remove the @Autowired annotations.
No @Autowired is needed. Since Spring Framework 4.3, when a class has a single constructor, Spring uses that constructor for injection automatically. The constructor can even be package-private, as here; Spring does not need it to be public.
What changed for production? At startup, Spring now resolves the two parameters first and only then creates the object, so if no PaymentClient bean exists, startup fails with a message that names the constructor parameter. The fields can never be null or replaced afterwards, and the class has no Spring import except @Service.
4What Changes for Tests
The test becomes ordinary Java. We build the object the same way Spring does, by calling its constructor.
5 messages in order. Play them, or step through them one at a time.
After the rewrite, the test talks to the class directly, like Spring does.
There is no Spring context, so the test runs in milliseconds. There is no reflection, so renaming a field cannot break it. And if someone adds a third dependency, every place that calls the constructor stops compiling, including this test, which tells us exactly what to update.
5The Lombok Shortcut
Teams that use Lombok can let it write the constructor. @RequiredArgsConstructor generates a constructor with one parameter for each final field that is not initialised, in declaration order.
The behaviour is identical to the hand-written version. The trade-off is that the constructor is now invisible in the source, so readers must know the annotation, and annotations on parameters, such as @Qualifier, need extra Lombok configuration (lombok.copyableAnnotations) to be copied onto the generated constructor. For two dependencies I usually write the constructor by hand; it is four lines.
6Follow-up questions
Should the constructor check for null arguments?
Spring never passes null for a required dependency, so in the Spring path a check adds nothing. In tests or manual construction it can catch mistakes early, and Objects.requireNonNull(repo, "repo") makes the failure clear at construction time instead of inside a method. Many teams skip it for brevity; either choice is reasonable if it is consistent.
Does this change anything for @SpringBootTest integration tests?
Not really. Spring still creates the bean, now through the constructor, and the test can still @Autowired the OrderService or replace a dependency with @MockitoBean (the replacement for the deprecated @MockBean in recent Spring versions; check your version). The big gain is in unit tests, which no longer need a context at all.
What if the class needs a dependency only in some cases?
Then that dependency should be explicit too, for example an ObjectProvider<FraudChecker> or an Optional<FraudChecker> constructor parameter. It still appears in the signature, so readers and tests see it, and the class can decide at runtime whether to use it.
7Conclusion
In this answer, we rewrote OrderService from field injection to constructor injection by making the fields private final and adding one constructor that takes both dependencies; with a single constructor Spring needs no @Autowired. Tests change the most: they call new OrderService(fakeRepo, mockPayments), run without a Spring context or reflection, and stop compiling when a dependency is added. Lombok's @RequiredArgsConstructor can generate the same constructor, with the small cost of hiding it from readers.
Open with
I would make both fields private and final and add a constructor, OrderService taking an OrderRepository and a PaymentClient, that assigns them, and I would remove the @Autowired annotations.
Then, if they want more
Because the class now has exactly one constructor, Spring uses it automatically; that has been the rule since Spring 4.3, and the constructor does not even need to be public.
In production the behaviour is the same, except that Spring resolves the dependencies before creating the object, so a missing PaymentClient fails startup with an error that names the parameter, and the fields can never be null or swapped later. The bigger change is in tests.
Before, a unit test had to create the object with the no-argument constructor and then push fakes into the fields, either directly, with ReflectionTestUtils, or with Mockito's InjectMocks, which silently leaves new dependencies null. After the rewrite, the test is plain Java: new OrderService with an in-memory repository and a mocked payment client.
There is no Spring context, so it runs in milliseconds, and if someone adds a third dependency, the test stops compiling and tells them what to pass. If the team uses Lombok, @RequiredArgsConstructor on the class generates the same constructor from the final fields, though for two dependencies I would usually just write it by hand.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 4
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Core technologies
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Rewrite this class to use constructor injection and explain what changes for tests:": https://scrivio-interview-library.netlify.app/spring-boot/dependency-injection/cba36e47b2/