java 为什么我必须在@Constructor 注解的 Spring 配置类中有一个默认构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29073254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:38:33  来源:igfitidea点击:

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

javaspringspring-mvcannotationsapplicationcontext

提问by Java Surfer

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.

我正在学习 Spring Core 认证,在提供的学习资料上,我有这个问题,但我无法给出答案。

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 @Configurationannotation. 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?

我没有在@Configuration注释所注释的配置类中声明任何构造函数。默认构造函数是超类继承的构造函数吗?要不然是啥?为什么我必须有一个默认构造函数而我不能覆盖它?

Tnx

田纳西州

回答by Vojtech Ruzicka

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

根据官方 spring javadoc,spring @Configuration 注释类需要具有默认的无参数构造函数

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

@Configuration 类必须具有默认/无参数构造函数,并且不能使用 @Autowired 构造函数参数。任何嵌套的配置类都必须是静态的

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

原因是 spring 使用CGLIB 来代理 @Configuration类,并且在 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 4 之前,基于 CGLIB 的代理类需要一个默认构造函数。而这不是CGLIB库的限制,而是Spring本身的限制。幸运的是,从 Spring 4 开始,这不再是问题。基于 CGLIB 的代理类不再需要默认构造函数。