Creating your own auto-configuration

简介: 44. Creating your own auto-configuration If you work in a company that develops shared libraries, or if you work on an open-source or com...

44. Creating your own auto-configuration

If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot.

Auto-configuration can be associated to a "starter" that provides the auto-configuration code as well as the typical libraries that you would use with it. We will first cover what you need to know to build your own auto-configuration and we will move on to the typical steps required to create a custom starter.

[Tip]

demo project is available to showcase how you can create a starter step by step.

44.1 Understanding auto-configured beans

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. This ensures that auto-configuration only applies when relevant classes are found and when you have not declared your own @Configuration.

You can browse the source code of spring-boot-autoconfigure to see the @Configuration classes that we provide (see the META-INF/spring.factories file).

44.2 Locating auto-configuration candidates

Spring Boot checks for the presence of a META-INF/spring.factories file within your published jar. The file should list your configuration classes under theEnableAutoConfiguration key.

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\
com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration

You can use the @AutoConfigureAfter or @AutoConfigureBefore annotations if your configuration needs to be applied in a specific order. For example, if you provide web-specific configuration, your class may need to be applied after WebMvcAutoConfiguration.

If you want to order certain auto-configurations that shouldn’t have any direct knowledge of each other, you can also use @AutoconfigureOrder. That annotation has the same semantic as the regular @Order annotation but provides a dedicated order for auto-configuration classes.

[Note]

Auto-configurations have to be loaded that way only. Make sure that they are defined in a specific package space and that they are never the target of component scan in particular.

44.3 Condition annotations

You almost always want to include one or more @Conditional annotations on your auto-configuration class. The @ConditionalOnMissingBean is one common example that is used to allow developers to ‘override’ auto-configuration if they are not happy with your defaults.

Spring Boot includes a number of @Conditional annotations that you can reuse in your own code by annotating @Configuration classes or individual @Beanmethods.

44.3.1 Class conditions

The @ConditionalOnClass and @ConditionalOnMissingClass annotations allows configuration to be included based on the presence or absence of specific classes. Due to the fact that annotation metadata is parsed using ASM you can actually use the value attribute to refer to the real class, even though that class might not actually appear on the running application classpath. You can also use the name attribute if you prefer to specify the class name using a String value.

[Tip]

If you are using @ConditionalOnClass or @ConditionalOnMissingClass as a part of a meta-annotation to compose your own composed annotations you must use name as referring to the class in such a case is not handled.

44.3.2 Bean conditions

The @ConditionalOnBean and @ConditionalOnMissingBean annotations allow a bean to be included based on the presence or absence of specific beans. You can use the value attribute to specify beans by type, or name to specify beans by name. The search attribute allows you to limit the ApplicationContext hierarchy that should be considered when searching for beans.

[Tip]

You need to be very careful about the order that bean definitions are added as these conditions are evaluated based on what has been processed so far. For this reason, we recommend only using @ConditionalOnBean and @ConditionalOnMissingBean annotations on auto-configuration classes (since these are guaranteed to load after any user-define beans definitions have been added).

[Note]

@ConditionalOnBean and @ConditionalOnMissingBean do not prevent @Configuration classes from being created. Using these conditions at the class level is equivalent to marking each contained @Bean method with the annotation.

44.3.3 Property conditions

The @ConditionalOnProperty annotation allows configuration to be included based on a Spring Environment property. Use the prefix and name attributes to specify the property that should be checked. By default any property that exists and is not equal to false will be matched. You can also create more advanced checks using the havingValue and matchIfMissing attributes.

44.3.4 Resource conditions

The @ConditionalOnResource annotation allows configuration to be included only when a specific resource is present. Resources can be specified using the usual Spring conventions, for example, file:/home/user/test.dat.

44.3.5 Web application conditions

The @ConditionalOnWebApplication and @ConditionalOnNotWebApplication annotations allow configuration to be included depending on whether the application is a 'web application'. A web application is any application that is using a Spring WebApplicationContext, defines a session scope or has a StandardServletEnvironment.

44.3.6 SpEL expression conditions

The @ConditionalOnExpression annotation allows configuration to be included based on the result of a SpEL expression.

44.4 Creating your own starter

A full Spring Boot starter for a library may contain the following components:

  • The autoconfigure module that contains the auto-configuration code.
  • The starter module that provides a dependency to the autoconfigure module as well as the library and any additional dependencies that are typically useful. In a nutshell, adding the starter should be enough to start using that library.
[Tip]

You may combine the auto-configuration code and the dependency management in a single module if you don’t need to separate those two concerns.

44.4.1 Naming

Please make sure to provide a proper namespace for your starter. Do not start your module names with spring-boot, even if you are using a different Maven groupId. We may offer an official support for the thing you’re auto-configuring in the future.

Here is a rule of thumb. Let’s assume that you are creating a starter for "acme", name the auto-configure module acme-spring-boot-autoconfigure and the starteracme-spring-boot-starter. If you only have one module combining the two, use acme-spring-boot-starter.

Besides, if your starter provides configuration keys, use a proper namespace for them. In particular, do not include your keys in the namespaces that Spring Boot uses (e.g. servermanagementspring, etc). These are "ours" and we may improve/modify them in the future in such a way it could break your things.

Make sure to trigger meta-data generation so that IDE assistance is available for your keys as well. You may want to review the generated meta-data (META-INF/spring-configuration-metadata.json) to make sure your keys are properly documented.

44.4.2 Autoconfigure module

The autoconfigure module contains everything that is necessary to get started with the library. It may also contain configuration keys definition (@ConfigurationProperties) and any callback interface that can be used to further customize how the components are initialized.

[Tip]

You should mark the dependencies to the library as optional so that you can include the autoconfigure module in your projects more easily. If you do it that way, the library won’t be provided and Spring Boot will back off by default.

44.4.3 Starter module

The starter is an empty jar, really. Its only purpose is to provide the necessary dependencies to work with the library; see it as an opinionated view of what is required to get started.

Do not make assumptions about the project in which your starter is added. If the library you are auto-configuring typically requires other starters, mention them as well. Providing a proper set of default dependencies may be hard if the number of optional dependencies is high as you should avoid bringing unnecessary dependencies for a typical usage of the library.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html

 

相关文章
|
存储 运维 安全
AIGC时代数据中心运维面临的挑战
AIGC时代数据中心运维面临的挑战
434 1
AIGC时代数据中心运维面临的挑战
|
7月前
|
弹性计算 关系型数据库 数据库
快速体验Cloudberry和APCC
通过Docker快速体验Cloudberry和APCC
384 6
|
7月前
|
存储 Oracle 关系型数据库
【赵渝强老师】Oracle的闪回删除
本文介绍了Oracle数据库的闪回删除(Flashback Drop)功能,该功能可从回收站恢复已删除的对象至删除前状态。文章详细讲解了回收站的工作原理及操作步骤,包括检查回收站功能是否开启、删除表、查看回收站内容以及使用闪回删除恢复数据等实战操作。通过具体示例,演示了如何恢复被删除的员工表及其数据,并处理同名表冲突问题。文末还附有视频讲解,帮助读者更直观地理解操作流程。
147 1
|
7月前
|
IDE 开发工具 C++
JetBrains CLion 2025.1 发布 - C 和 C++ 跨平台 IDE
JetBrains CLion 2025.1 (macOS, Linux, Windows) - C 和 C++ 跨平台 IDE
330 0
|
存储 人工智能 供应链
区块链技术在供应链金融中的革新应用
区块链技术在供应链金融中的革新应用
1811 20
|
机器学习/深度学习 存储 人工智能
使用 CTransformers 运行 Zephyr-7b、Mistral-7b 模型
使用 CTransformers 运行 Zephyr-7b、Mistral-7b 模型
465 0
|
Android开发
【苹果安卓通用】xlsx 和 vCard 文件转换器,txt转vCard文件格式,CSV转 vCard格式,如何批量号码导入手机通讯录,一篇文章说全
本文介绍了如何快速将批量号码导入手机通讯录,适用于企业客户管理、营销团队、活动组织、团队协作和新员工入职等场景。步骤包括:1) 下载软件,提供腾讯云盘和百度网盘链接;2) 打开软件,复制粘贴号码并进行加载预览和制作文件;3) 将制作好的文件通过QQ或微信发送至手机,然后按苹果、安卓或鸿蒙系统的指示导入。整个过程简便快捷,可在1分钟内完成。
774 6
QGIS【实例 01】筛选范围内的数据相交intersection工具使用及Feature (347897) has invalid geometry问题处理
QGIS【实例 01】筛选范围内的数据相交intersection工具使用及Feature (347897) has invalid geometry问题处理
752 0
|
安全 测试技术
NAT基础一览
NAT基础一览
|
Arthas Java 测试技术
深入Spring Boot:利用Arthas排查NoSuchMethodError
## 前言 有时spring boot应用会遇到`java.lang.NoSuchMethodError`的问题,下面以具体的demo来说明怎样利用[arthas](https://github.com/alibaba/arthas)来排查。 Demo: https://github.com/hengyunabc/spring-boot-inside/tree/master/dem
2829 0