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 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.


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.


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.


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.


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).


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

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.


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

 

时间: 2024-11-10 00:26:07

Creating your own auto-configuration的相关文章

SpringBootApplication注解 专题

到这里,看到所有的配置是借助SpringFactoriesLoader加载了META-INF/spring.factories文件里面所有符合条件的配置项的全路径名.找到spring-boot-autoconfigure包,看到META-INF下的spring.factories文件(果然是你,果然),这里就是自动化配置所有类项的列表. /** * General purpose factory loading mechanism for internal use within the fram

J2ME MIDP Currency Converter Tutorial for NetBeans IDE 4.0

j2me MIDP Currency Converter Tutorial for NetBeans IDE 4.0Feedback http://www.netbeans.org/kb/articles/tutorial-currencyconverter-40.html Feedback The Currency Converter application you will build in this tutorial shows you how to: start a j2me MIDP

IPv6是什么?IPv6的特点与优势

IPv6是Internet Protocol Version 6的缩写,其中Internet Protocol译为"互联网协议".IPv6是IETF(互联网工程任务组,Internet Engineering Task Force)设计的用于替代现行版本IP协议(IPv4)的下一代IP协议.目前IP协议的版本号是4(简称为IPv4),它的下一个版本就是IPv6. IPv6是"Internet Protocol Version 6"的缩写,它是IETF设计的用于替代现

BIOS 设置详解

AWARD BIOS AWARD BIOS是目前应用最为广泛的一种BIOS.本文将详细介绍一下AWARD BIOS中的有关设置选项的含义和设置方法,在AWARD BIOS的主菜单中主要有以下几个菜单项: Standard CMOS Setup(标准CMOS设定): 这个选项可以设置系统日期.时间.IDE设备.软驱A与B.显示系统的类型.错误处理方法等. (1)在IDE设备设置中,用户可以在Type(类型)和Mode(模式)项设为Auto,使每次启动系统时BIOS自动检测硬盘.也可以在主菜单中的I

bios里面怎么设置内存

  Above 1MB Memory Test:设置开机自检时是否检测1M以上内存.该选项已经在新的BIOS中被淘汰.由于内存价格暴跌,电脑用户安装内存容量陡然增加,开机时的大容量内存自检时间太长,今后,即使一遍的内存检测可能也会出现允许/禁止开关. Auto Configuration:设置为允许时,BIOS按照最佳状态设置.BIOS可以自动设置内存定时,因此会禁止一些对内存设置的修改,建议选择允许方式. Memory Test Tick Sound:是否发出内存自检的滴嗒声.如果您闲它烦,可

ganglia man page : gmond gmetad gmetad.py gmetric gstat gmond.conf

gmond GMOND(1) User Commands GMOND(1) NAME gmond - manual page for Ganglia Monitor Daemon SYNOPSIS gmond [OPTIONS]... DESCRIPTION The Ganglia Monitoring Daemon (gmond) listens to the cluster message channel, stores the data in-memory and when request

GitHub Flavored Markdown viewer plugin for Eclipse

GitHub Flavored Markdown viewer plugin for Eclipse This project provides an Eclipse view which provides a reasonably accurate presentation of GithHub Flavored Markdown files. Usage After installation (see below), the viewer may be accessed in any of

TCP/IP协议 详解

Transmission Control Protocol/Internet Protocol的简写,中译名为传输控制协议/因特网互联协议,又名网络通讯协议,是Internet最基本的协议.Internet国际互联网络的基础,由网络层的IP协议和传输层的TCP协议组成.TCP/IP 定义了电子设备如何连入因特网,以及数据如何在它们之间传输的标准.协议采用了4层的层级结构,每一层都呼叫它的下一层所提供的网络来完成自己的需求.通俗而言:TCP负责发现传输的问题,一有问题就发出信号,要求重新传输,直到

ELK日志收集错误,elasticsearch日志抛错

问题描述 ELK日志收集错误,elasticsearch日志抛错 问题描述: 我用logstash收集日志,保存到elasticsearch 每天都会按日期建立新的索引.但是elasticsearch日志显示,建立索引之后,有错误日志, [2016-03-30 08:00:03,002][INFO ][cluster.metadata ] [log_master] [union_user-2016-03-30] creating index, cause [auto(bulk api)], te

如何在Kali Linux环境下设置蜜罐

Pentbox 是一个包含了许多可以使渗透测试工作变得简单流程化的工具的安全套件.它是用 Ruby 编写并且面向 GNU / Linux,同时也支持 Windows.MacOS 和其它任何安装有 Ruby 的系统.在这篇短文中我们将讲解如何在 Kali Linux 环境下设置蜜罐.如果你还不知道什么是蜜罐honeypot,"蜜罐是一种计算机安全机制,其设置用来发现.转移.或者以某种方式,抵消对信息系统的非授权尝试." 下载 Pentbox: 在你的终端中简单的键入下面的命令来下载 pe