为什么我必须在Spring配置类中使用@Configuration批注注释的默认构造函数? [英] Why I must have a default constructor in a Spring configuration class annoted by the @Configuration annotation?
问题描述
我正在学习Spring Core认证,在提供的学习材料上,我有这个问题,但我无法给出答案.
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.
为什么必须在@Configuration中具有默认构造函数带注释的课程?
Why must you have to have a default constructor in your @Configuration annotated class?
我没有在由 @Configuration 注释注释的配置类中声明任何构造函数.默认构造函数是超类继承的构造函数吗?还是什么?为什么我必须有一个默认构造函数,却不能覆盖它?
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
推荐答案
According to official spring javadoc, spring @Configuration annotated classes are required to have default no-arg constructor
@Configuration类必须具有默认/无参数构造函数,并且不得使用@Autowired构造函数参数.任何嵌套的配置类都必须是静态的
@Configuration classes must have a default/no-arg constructor and may not use @Autowired constructor parameters. Any nested configuration classes must be static
原因是spring使用 CGLIB进行代理@Configuration 类,并且在Spring中有限制,使用版本4之前的CGLIB代理的类必须具有默认的无参数构造函数.
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.
在Spring 4之前,基于CGLIB的代理类需要默认的构造函数.这不是CGLIB库的限制,而是Spring本身.幸运的是,从Spring 4开始,这不再是问题.基于CGLIB的代理类不再需要默认的构造函数.
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.
这篇关于为什么我必须在Spring配置类中使用@Configuration批注注释的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!