为什么我必须在 @Configuration 注释的 Spring 配置类中有一个默认构造函数? [英] Why I must have a default constructor in a Spring configuration class annoted by the @Configuration annotation?

查看:65
本文介绍了为什么我必须在 @Configuration 注释的 Spring 配置类中有一个默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 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

推荐答案

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

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.

这篇关于为什么我必须在 @Configuration 注释的 Spring 配置类中有一个默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆