Spring Boot 自动配置类应该使用 @Configuration 注解吗?
根据我的测试,我发现 Spring Boot 自动配置类有或没有 @Configuration 注释时没有明显的区别 - 如果它们是在 spring.factories 中配置的code> 正确加载,无论 @Configuration
注释如何。
但是,似乎每个自定义自动配置示例和演示都使用 @Configuration
注释。所有这些示例都使用 @Configuration 是否有原因(或者只是约定)?不使用@Configuration
有什么影响吗?
在自动配置类上使用 @Configuration
的一些示例:
- https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.developing-auto-configuration.condition-annotations.class-conditions
- https://www.baeldung.com/spring-boot-custom-auto-configuration#creating-a-custom-auto-configuration
- https://www.baeldung.com/spring-boot-custom-starter#1-auto-configuration-classes
- https://www.javadevjournal.com/spring-boot/spring-boot-custom-starter/
- https://billykorando.com/2019/12/30 /building-a-custom-spring-boot-starter/
- http://www.masterspringboot.com/getting-started-with-spring-boot/spring-boot-quickstarts/how-to-build-a-custom-spring-boot-starter-in-no-time /
- https://github.com/snicoll/spring-boot-master-auto-configuration/blob/main/hornetq-spring-boot-autoconfigure/src/main/java/hornetq/autoconfigure/HornetQAutoConfiguration.java
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,他们应该是。该文档指出 自动配置类应该用
@Configuration
注释:如果您不使用
@Configuration
注释它们,您将依赖 Spring Framework 的 “lite”@Bean 模式。这改变了自动配置类的行为。由于实施不符合记录的要求,因此不保证将来可以正常工作。Yes, they should be. The documentation states that an auto-configuration class should be annotated with
@Configuration
: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.@Autoconfiguration内部使用配置注解,proxyBeanMethods= false,
@Autoconfiguration internally uses configuration annotation with proxyBeanMethods= false,