16

I am studying for Spring Core certification and, on the provided study stuff, I have this question but I can't give an answer to it.

Why must you have to have a default constructor in your @Configuration annotated class?

I don't declare any constructor into my configuration classes annoted by the @Configuration annotation. The default constructor is the one inherited by the super class? or what? Why I must have a default constructor and I can't override it?

Tnx

ScanQR
  • 3,740
  • 1
  • 13
  • 30
Java Surfer
  • 613
  • 3
  • 9
  • 13
  • 1
    Guess it means you need a constructor without parameters. So you can override constructor but it need a constructor without parameters to create the Configuration. – StanislavL Mar 16 '15 at 09:27

1 Answers1

28

According to official spring javadoc, spring @Configuration annotated classes are required to have default no-arg constructor

@Configuration classes must have a default/no-arg constructor and may not use @Autowired constructor parameters. Any nested configuration classes must be static

The reason is that spring uses CGLIB to proxy @Configuration classes and there is limitation in Spring, that classes proxied with CGLIB prior to version 4 are required to have default no-args constructor.

Prior to Spring 4, CGLIB-based proxy classes require a default constructor. And this is not the limitation of CGLIB library, but Spring itself. Fortunately, as of Spring 4 this is no longer an issue. CGLIB-based proxy classes no longer require a default constructor.

Vojtech Ruzicka
  • 16,384
  • 15
  • 63
  • 66
  • I have already read the documentation but it only say that class annoted with @Configuration require a default no-arg constructor but don't explain why – Java Surfer Mar 16 '15 at 09:33
  • 4
    Default constructors imo are a cause of bad design, since it forces objects to be mutable - by requiring setters for properties. I steer away from Spring magic annotations, and try to keep all Spring dependencies in a package that contain all my config files, and I control all my dependencies and the IoC in there in an explicit manner. – Charbel Mar 08 '16 at 11:28
  • 1
    This is a really old answer but perhaps you can still help. I am still seeing "Superclass has no null constructors but no arguments were given" when trying to create a proxy, even though I am on Spring 4.x. I thought that default constructors were no longer mandatory. – kennyg Dec 11 '17 at 22:35
  • 3
    Spring 5.* doesn't require no-args default constructor. – Laplas Jan 31 '19 at 11:08