I have a Spring component that has 8 members.
I am currently autowiring these 8 members with field injection.
I now want make these members private final, and do constructor injection to set them.
This is easy enough to do, but now I have a component constructor with 8 parameters.
I know I can use setter injection and set these values in an XML file, but this I don't want to do.
Are there any other alternatives?
EDIT:
This component just does a single thing. But that involves calling several other services. Hence the 8 injections
Firstly, there is no alternative.
Secondly, if a contructor has 8 parameters, it is not designed properly. I think you should rethink about the class structure and responsibility. Consider splitting the class into two or three separate beans and inject those.
If a constructor has 8 arguments, in most cases it will be vioalating SRP(Single Responsibility principle)
There is an option if you are happy to introduce Project Lombok. Given the following class:
@Component
@RequiredArgsConstructor
public class ThankingService {
private final Translator translator;
public String produce() {
return translator.translate("thank you");
}
}
The Lombok annotation @RequiredArgsConstructor will cause Lombok to generate a constructor, this happens if there is 1 data variable or 10, etc.
@Component
public class ThankingService {
private final Translator translator;
public String thank() {
return translator.translate("thank you");
}
/* Generated by Lombok */
public ThankingService(Translator translator) {
this.translator = translator;
}
}
More info: https://www.baeldung.com/spring-injection-lombok
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With