1

As mentioned in the answers to this question, Spring can invoke private constructors through reflection.

Generally when we create a class with a private constructor, we use it for preventing instantiation outside of the class as in the case of a Singleton class, or for preventing instantiation of classes with static utility methods/constants.

What is the reason why Spring allows beans with private constructors to be instantiated ?

1 Answers1

0

You would have to ask the Spring developers. It's probably a matter of convenience.

  • It allows you to create Classes that cannot be instantiated except through the Spring Container, or other reflection based technique.

  • It allows you to require your Java code to use other constructors which require different inputs.

If Spring could not use a private or package access constructor then you would have to declare constructors with public access. Your Java code could then use them. Your intent not to use classes this way would not be so clear.

joshp
  • 1,886
  • 2
  • 20
  • 28