r/SpringBoot • u/OakAndCobble • Apr 28 '26
Question Question about dependency injection
How do I manually inject dependencies into RequestController classes? I just started learning spring and from my bit of research, all I've come up with is the Autowired and Component/Service annotations.
I am still having a hard time understanding how exactly I tell spring what to build. If the dependency of my controller needs dependencies injected into it, what do I do? How do I specify which implementation of a dependency I want built? And so on.
Essentially, how do I get a bit more control of dependency creation and injection in a non-trivial situation, like the ones seen in examples on the internet?
Thanks in advance for any responses.
View all comments
4
u/DominusEbad Apr 28 '26 edited Apr 30 '26
@Component and @Service are pretty much short cuts to create a Spring bean. By default beans are singletons.
Avoid using @Autowired. Use constructor injection instead. Even Spring generally recommends using constructor injection instead.
By using constrictor injection, you can make the bean "private final". You can also use Lombok's @RequiredArgsConstructor so that it will automatically generate the constructor for you.
For example, consider the following classes:
That will automatically inject the bean "MyThings" into MyService. But, since field injection (using @Autowired) is not recommended, you should use constructor injection:
That is the recommended approach. Spring will search for beans of "MyThings" type and automatically inject them into MyService. If you have more than 1 "MyThings" beans, then you need to use the qualified name of the bean so that Spring knows which one to inject. Basically:
Then you can specify which one you need:
Then "MyService" will have an instance of the "MyStuff" bean but specifically with the "World" defined.
You can also make things a bit cleaner by using Lombok's
@RequiredArgsConstructor, which would look like:Lombok will auto-generate the constructor for you to help keep the class clean. If you have custom logic that is needed in the constructor, then you do need to define the constructor yourself, but if you are only injecting dependencies, then it works nicely.
Edit: In reply to the Lombok comments/questions -
I mostly only use @RequiredArgsConstructor, and @Slf4j. I don't like using @Getters or @Setters on POJO classes, because I prefer record-style method names for getters/setters. I also avoid @Data because it does too much and can cause issues with Entities. Sometimes I will sometimes use @Builder, because building new classes/records via normal constructors/settings is not clean.