Spring Boot 自动配置类应该使用 @Configuration 注解吗?

发布于 2025-01-13 02:40:52 字数 2313 浏览 6 评论 0 原文

根据我的测试,我发现 Spring Boot 自动配置类有或没有 @Configuration 注释时没有明显的区别 - 如果它们是在 spring.factories 中配置的code> 正确加载,无论 @Configuration 注释如何。

但是,似乎每个自定义自动配置示例和演示都使用 @Configuration 注释。所有这些示例都使用 @Configuration 是否有原因(或者只是约定)?不使用@Configuration有什么影响吗?

在自动配置类上使用 @Configuration 的一些示例:

Based on my testing, I've found no obvious difference when Spring Boot auto-configuration classes have or don't have the @Configuration annotation - if they are configured in spring.factories correctly they are loaded regardless of the @Configuration annotation.

However, it seems like every custom auto-configuration example and demo uses the @Configuration annotation. Is there a reason all these examples use @Configuration (or is it just convention)? Is there any impact to not using @Configuration?

Some examples that use @Configuration on auto-configuration classes:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鲜血染红嫁衣 2025-01-20 02:40:52

是的,他们应该是。该文档指出 自动配置类应该用@Configuration注释:

在底层,自动配置是通过标准@Configuration类实现的。附加的 @Conditional 注释用于限制何时应用自动配置。通常,自动配置类使用 @ConditionalOnClass@ConditionalOnMissingBean 注解。

如果您不使用 @Configuration 注释它们,您将依赖 Spring Framework 的 “lite”@Bean 模式。这改变了自动配置类的行为。由于实施不符合记录的要求,因此不保证将来可以正常工作。

Yes, they should be. The documentation states that an auto-configuration class should be annotated with @Configuration:

Under the hood, auto-configuration is implemented with standard @Configuration classes. Additional @Conditional annotations are used to constrain when the auto-configuration should apply. Usually, auto-configuration classes use @ConditionalOnClass and @ConditionalOnMissingBean annotations.

If you do not annotate them with @Configuration you are relying upon Spring Framework’s “lite” @Bean mode. This changes the behaviour of the auto-configuration classes. It is not guaranteed to work in the future as the implementation does not meet the documented requirements.

人│生佛魔见 2025-01-20 02:40:52

@Autoconfiguration内部使用配置注解,proxyBeanMethods= false,

@Configuration(proxyBeanMethods = false)

@Autoconfiguration internally uses configuration annotation with proxyBeanMethods= false,

@Configuration(proxyBeanMethods = false)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文