Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I must have a default constructor in a Spring configuration class annoted by the @Configuration annotation?

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

like image 902
Java Surfer Avatar asked Mar 16 '15 09:03

Java Surfer


People also ask

Why do we need a default constructor in Spring boot?

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.

What is the use of @configuration annotation in Spring?

One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework.

Is default constructor mandatory in Spring?

It's not mandatory to define default constructor, but if you are writing Hibernate persistent class, JPA entities, or using the Spring framework to manage object creation and wiring dependencies, you need to be a bit careful.

What is the purpose of default constructor?

The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.


1 Answers

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.

like image 71
Vojtech Ruzicka Avatar answered Oct 26 '22 19:10

Vojtech Ruzicka