Spring constructor injection with lots of fields

Viewed 2286

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

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)

First of all you can set the initial values of these parameters in an .properties file and then read this property file as a pojo configuration class and it is very easy in spring to convert .properties file into pojo.

so the constructor will be something like this

@Autowired public Temp(ConfigPojoClass config) { ..... }

Related