Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring constructor injection with lots of fields

Tags:

java

spring

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

like image 993
Somaiah Kumbera Avatar asked Sep 11 '25 15:09

Somaiah Kumbera


2 Answers

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)

like image 111
pvpkiran Avatar answered Sep 14 '25 08:09

pvpkiran


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

like image 43
boardtc Avatar answered Sep 14 '25 06:09

boardtc