Spring Configuration Processor是一个强大的工具,它用于处理Spring框架中的配置元数据

Spring Configuration Processor是在编译时自动生成配置元数据的工具,用于IDE中的属性提示和代码补全。它处理@ConfigurationProperties注解的类,但也支持手动编写元数据以应对特殊情况。元数据文件包含属性、组和提示信息,帮助开发者更好地理解和配置应用的属性。属性可以有默认值,且支持废弃和替换属性。同时,通过ValueHint和ValueProvider提供有效值的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Configuration Processor是一个强大的工具,它用于处理Spring框架中的配置元数据。这个工具主要通过注解处理器在编译时生成配置属性的元数据,从而使得开发者能够在IDE中或者通过其他工具更方便地查看和使用这些配置属性。

具体功能包括:

  1. 自动生成配置元数据:Spring Configuration Processor会在编译时扫描带有@ConfigurationProperties注解的类,并生成相应的元数据文件(通常是.properties.yaml格式)。
  2. 提高开发效率:通过生成的元数据文件,开发者可以更轻松地理解和编辑配置文件,因为文件中会包含每个配置项的类型、默认值和描述信息。
  3. 集成IDE支持:许多现代IDE(如IntelliJ IDEA和Eclipse)都支持直接读取和使用这些元数据文件,提供智能提示和自动补全功能,极大地提升了开发体验。
  4. 减少错误:由于元数据文件的存在,编译器可以在编译阶段就检查出一些常见的配置错误,减少了运行时出错的可能性。
    Spring Configuration Processor是Spring框架中用于处理Java配置类的一种机制。它允许开发者通过注解的方式定义Bean,而不是传统的XML配置文件。这种方式使得配置更加简洁和易于维护。

具体来说,Spring Configuration Processor的工作原理如下:

  1. 组件扫描:Spring容器会扫描指定的包或类路径,寻找带有@Component, @Service, @Repository, @Controller等注解的类。这些类会被自动注册为Spring的Bean。

  2. 注解驱动的配置:在配置类上使用@Configuration注解来标识这是一个配置类。配置类内部可以使用@Bean注解来定义Bean的方法,这些方法的返回值将会被注册为Spring容器中的Bean。

  3. 依赖注入:在配置类中,可以通过构造器、setter方法或者字段注入的方式来实现依赖注入。Spring容器会根据类型匹配自动注入相应的依赖。

  4. 条件装配:Spring支持基于条件的装配,例如只有在某个类存在时才创建某个Bean,或者根据环境变量来决定是否创建某个Bean。这可以通过@Conditional相关的注解来实现。

  5. 属性配置:可以通过@Value注解来注入外部化的属性值,如配置文件中的值或者系统环境变量。

  6. 事件监听:Spring提供了事件发布-订阅模型,可以在应用程序的不同阶段触发事件,并通过监听器来响应这些事件。

  7. 后置处理器:Spring允许在Bean初始化之后执行一些额外的操作,这可以通过实现BeanPostProcessor接口来实现。

  8. 异步执行:Spring支持异步方法执行,可以通过@Async注解来声明一个方法是异步执行的。

  9. 事务管理:Spring提供了声明式事务管理,可以通过@Transactional注解来简化事务的管理。

  10. AOP支持:Spring AOP(面向切面编程)允许你定义横切关注点,如日志记录、性能监控等,而不需要修改业务逻辑代码。

Getting Started
Reference Documentation

For further reference, please consider the following sections:

Official Apache Maven documentation
Spring Boot Maven Plugin Reference Guide
Create an OCI image
Spring Configuration Processor

Appendix B: Configuration Metadata

Spring Boot jars include metadata files that provide details of all supported configuration properties. The files are designed to let IDE developers offer contextual help and “code completion” as users are working with application.properties or application.yml files.

The majority of the metadata file is generated automatically at compile time by processing all items annotated with @ConfigurationProperties. However, it is possible to write part of the metadata manually for corner cases or more advanced use cases.
10.B.1. Metadata Format

Configuration metadata files are located inside jars under META-INF/spring-configuration-metadata.json. They use a simple JSON format with items categorized under either “groups” or “properties” and additional values hints categorized under “hints”, as shown in the following example:


{
   "groups": [
    {
   
        "name": "server",
        "type": "org.springframework.boot.autoconfigure.web.ServerProperties",
        "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
    },
    {
   
        "name": "spring.jpa.hibernate",
        "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
        "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
        "sourceMethod": "getHibernate()"
    }
    ...
],"properties": [
    {
   
        "name": "server.port",
        "type": "java.lang.Integer",
        "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
    },
    {
   
        "name": "server.address",
        "type": "java.net.InetAddress",
        "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
    },
    {
   
          "name": "spring.jpa.hibernate.ddl-auto",
          "type": "java.lang.String",
          "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.",
          "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
    }
    ...
],"hints": [
    {
   
        "name": "spring.jpa.hibernate.ddl-auto",
        "values": [
            {
   
                "value": "none",
                "description": "Disable DDL handling."
            },
            {
   
                "value": "validate",
                "description": "Validate the schema, make no changes to the database."
            },
            {
   
                "value": "update",
                "description": "Update the schema if necessary."
            },
            {
   
                "value": "create",
                "description": "Create the schema and destroy previous data."
            },
            {
   
                "value": "create-drop",
                "description": "Create and then destroy the schema at the end of the session."
            }
        ]
    }
]}

Each “property” is a configuration item that the user specifies with a given value. For example, server.port and server.address might be specified in application.properties, as follows:

server.port=9090
server.address=127.0.0.1

The “groups” are higher level items that do not themselves specify a value but instead provide a contextual grouping for properties. For example, the server.port and server.address properties are part of the server group.
It is not required that every “property” has a “group”. Some properties might exist in their own right.

Finally, “hints” are additional information used to assist the user in configuring a given property. For example, when a developer is configuring the spring.jpa.hibernate.ddl-auto property, a tool can use the hints to offer some auto-completion help for the none, validate, update, create, and create-drop values.
Group Attributes

The JSON object contained in the groups array can contain the attributes shown in the following table:
Name Type Purpose

name

String

The full name of the group. This attribute is mandatory.

type

String

The class name of the data type of the group. For example, if the group were based on a class annotated with @ConfigurationProperties, the attribute would contain the fully qualified name of that class. If it were based on a @Bean method, it would be the return type of that method. If the type is not known, the attribute may be omitted.

description

String

A short description of the group that can be displayed to users. If no description is available, it may be omitted. It is recommended that descriptions be short paragraphs, with the first line providing a concise summary. The last line in the description should end with a period (.).

sourceType

String

The class name of the source that contributed this group. For example, if the group were based on a @Bean method annotated with @ConfigurationProperties, this attribute would contain the fully qualified name of the @Configuration class that contains the method. If the source type is not known, the attribute may be omitted.

sourceMethod

String

The full name of the method (include parenthesis and argument types) that contributed this group (for example, the name of a @ConfigurationProperties annotated @Bean method). If the source method is not known, it may be omitted.
Property Attributes

The JSON object contained in the properties array can contain the attributes described in the following table:
Name Type Purpose

name

String

The full name of the property. Names are in lower-case period-separated form (for example, server.address). This attribute is mandatory.

type

String

The full signature of the data type of the property (for example, java.lang.String) but also a full generic type (such as java.util.Map<java.lang.String,acme.MyEnum>). You can use this attribute to guide the user as to the types of values that they can enter. For consistency, the type of a primitive is specified by using its wrapper counterpart (for example, boolean becomes java.lang.Boolean). Note that this class may be a complex type that gets converted from a String as values are bound. If the type is not known, it may be omitted.

description

String

A short description of the property that can be displayed to users. If no description is available, it may be omitted. It is recommended that descriptions be short paragraphs, with the first line providing a concise summary. The last line in the description should end with a period (.).

sourceType

String

The class name of the source that contributed this property. For example, if the property were from a class annotated with @ConfigurationProperties, this attribute would contain the fully qualified name of that class. If the source type is unknown, it may be omitted.

defaultValue

Object

The default value, which is used if the property is not specified. If the type of the property is an array, it can be an array of value(s). If the default value is unknown, it may be omitted.

deprecation

Deprecation

Specify whether the property is deprecated. If the field is not deprecated or if that information is not known, it may be omitted. The next table offers more detail about the deprecation attribute.

The JSON object contained in the deprecation attribute of each properties element can contain the following attributes:
Name Type Purpose

level

String

The level of deprecation, which can be either warning (the default) or error. When a property has a warning deprecation level, it should still be bound in the environment. However, when it has an error deprecation level, the property is no longer managed and is not bound.

reason

String

A short description of the reason why the property was deprecated. If no reason is available, it may be omitted. It is recommended that descriptions be short paragraphs, with the first line providing a concise summary. The last line in the description should end with a period (.).

replacement

String

The full name of the property that replaces this deprecated property. If there is no replacement for this property, it may be omitted.
Prior to Spring Boot 1.3, a single deprecated boolean attribute can be used instead of the deprecation element. This is still supported in a deprecated fashion and should no longer be used. If no reason and replacement are available, an empty deprecation object should be set.

Deprecation can also be specified declaratively in code by adding the @DeprecatedConfigurationProperty annotation to the getter exposing the deprecated property. For instance, assume that the app.acme.target property was confusing and was renamed to app.acme.name. The following example shows how to handle that situation:

@ConfigurationProperties(“app.acme”)
public class AcmeProperties {

    private String name;

    public String getName() {
    ... }

    public void setName(String name) {
    ... }

    @DeprecatedConfigurationProperty(replacement = "app.acme.name")
    @Deprecated
    public String getTarget() {
   
        return getName();
    }

    @Deprecated
    public void setTarget(String target) {
   
        setName(target);
    }
}
There is no way to set a level. warning is always assumed, since code is still handling the property.

The preceding code makes sure that the deprecated property still works (delegating to the name property behind the scenes). Once the getTarget and setTarget methods can be removed from your public API, the automatic deprecation hint in the metadata goes away as well. If you want to keep a hint, adding manual metadata with an error deprecation level ensures that users are still informed about that property. Doing so is particularly useful when a replacement is provided.
Hint Attributes

The JSON object contained in the hints array can contain the attributes shown in the following table:
Name Type Purpose

name

String

The full name of the property to which this hint refers. Names are in lower-case period-separated form (such as spring.mvc.servlet.path). If the property refers to a map (such as system.contexts), the hint either applies to the keys of the map (system.contexts.keys) or the values (system.contexts.values) of the map. This attribute is mandatory.

values

ValueHint[]

A list of valid values as defined by the ValueHint object (described in the next table). Each entry defines the value and may have a description.

providers

ValueProvider[]

A list of providers as defined by the ValueProvider object (described later in this document). Each entry defines the name of the provider and its parameters, if any.

The JSON object contained in the values attribute of each hint element can contain the attributes described in the following table:
Name Type Purpose

value

Object

A valid value for the element to which the hint refers. If the type of the property is an array, it can also be an array of value(s). This attribute is mandatory.

description

String

A short description of the value that can be displayed to users. If no description is available, it may be omitted. It is recommended that descriptions be short paragraphs, with the first line providing a concise summary. The last line in the description should end with a period (.).

The JSON object contained in the providers attribute of each hint element can contain the attributes described in the following table:
Name Type Purpose

name

String

The name of the provider to use to offer additional content assistance for the element to which the hint refers.

parameters

JSON object

Any additional parameter that the provider supports (check the documentation of the provider for more details).
Repeated Metadata Items

Objects with the same “property” and “group” name can appear multiple times within a metadata file. For example, you could bind two separate classes to the same prefix, with each having potentially overlapping property names. While the same names appearing in the metadata multiple times should not be common, consumers of metadata should take care to ensure that they support it.
10.B.2. Providing Manual Hints

To improve the user experience and further assist the user in configuring a given property, you can provide additional metadata that:

Describes the list of potential values for a property.

Associates a provider, to attach a well defined semantic to a property, so that a tool can discover the list of potential values based on the project’s context.

Value Hint

The name attribute of each hint refers to the name of a property. In the initial example shown earlier, we provide five values for the spring.jpa.hibernate.ddl-auto property: none, validate, update, create, and create-drop. Each value may have a description as well.

If your property is of type Map, you can provide hints for both the keys and the values (but not for the map itself). The special .keys and .values suffixes must refer to the keys and the values, respectively.

Assume a sample.contexts maps magic String values to an integer, as shown in the following example:


@ConfigurationProperties("sample")
public class SampleProperties {
   

    private Map<String,Integer> contexts;
    // getters and setters
}

The magic values are (in this example) are sample1 and sample2. In order to offer additional content assistance for the keys, you could add the following JSON to the manual metadata of the module:

{
   "hints": [
    {
   
        "name": "sample.contexts.keys",
        "values": [
            {
   
                "value": "sample1"
            },
            {
   
                "value": "sample2"
            }
        ]
    }
]}
We recommend that you use an Enum for those two values instead. If your IDE supports it, this is by far the most effective approach to auto-completion.

Value Providers

Providers are a powerful way to attach semantics to a property. In this section, we define the official providers that you can use for your own hints. However, your favorite IDE may implement some of these or none of them. Also, it could eventually provide its own.
As this is a new feature, IDE vendors must catch up with how it works. Adoption times naturally vary.

The following table summarizes the list of supported providers:
Name Description

any

Permits any additional value to be provided.

class-reference

Auto-completes the classes available in the project. Usually constrained by a base class that is specified by the target parameter.

handle-as

Handles the property as if it were defined by the type defined by the mandatory target parameter.

logger-name

Auto-completes valid logger names and logger groups. Typically, package and class names available in the current project can be auto-completed as well as defined groups.

spring-bean-reference

Auto-completes the available bean names in the current project. Usually constrained by a base class that is specified by the target parameter.

spring-profile-name

Auto-completes the available Spring profile names in the project.
Only one provider can be active for a given property, but you can specify several providers if they can all manage the property in some way. Make sure to place the most powerful provider first, as the IDE must use the first one in the JSON section that it can handle. If no provider for a given property is supported, no special content assistance is provided, either.
Any

The special any provider value permits any additional values to be provided. Regular value validation based on the property type should be applied if this is supported.

This provider is typically used if you have a list of values and any extra values should still be considered as valid.

The following example offers on and off as auto-completion values for system.state:

{
   "hints": [
    {
   
        "name": "system.state",
        "values": [
            {
   
                "value": "on"
            },
            {
   
                "value": "off"
            }
        ],
        "providers": [
            {
   
                "name": "any"
            }
        ]
    }
]}

Note that, in the preceding example, any other value is also allowed.
Class Reference

The class-reference provider auto-completes classes available in the project. This provider supports the following parameters:
Parameter Type Default value Description

target

String (Class)

none

The fully qualified name of the class that should be assignable to the chosen value. Typically used to filter out-non candidate classes. Note that this information can be provided by the type itself by exposing a class with the appropriate upper bound.

concrete

boolean

true

Specify whether only concrete classes are to be considered as valid candidates.

The following metadata snippet corresponds to the standard server.servlet.jsp.class-name property that defines the JspServlet class name to use:

{
   "hints": [
    {
   
        "name": "server.servlet.jsp.class-name",
        "providers": [
            {
   
                "name": "class-reference",
                "parameters": {
   
                    "target": "javax.servlet.http.HttpServlet"
                }
            }
        ]
    }
]}


Handle As

The handle-as provider lets you substitute the type of the property to a more high-level type. This typically happens when the property has a java.lang.String type, because you do not want your configuration classes to rely on classes that may not be on the classpath. This provider supports the following parameters:
Parameter Type Default value Description

target

String (Class)

none

The fully qualified name of the type to consider for the property. This parameter is mandatory.

The following types can be used:

Any java.lang.Enum: Lists the possible values for the property. (We recommend defining the property with the Enum type, as no further hint should be required for the IDE to auto-complete the values)

java.nio.charset.Charset: Supports auto-completion of charset/encoding values (such as UTF-8)

java.util.Locale: auto-completion of locales (such as en_US)

org.springframework.util.MimeType: Supports auto-completion of content type values (such as text/plain)

org.springframework.core.io.Resource: Supports auto-completion of Spring’s Resource abstraction to refer to a file on the filesystem or on the classpath (such as classpath:/sample.properties)

If multiple values can be provided, use a Collection or Array type to teach the IDE about it.

The following metadata snippet corresponds to the standard spring.liquibase.change-log property that defines the path to the changelog to use. It is actually used internally as a org.springframework.core.io.Resource but cannot be exposed as such, because we need to keep the original String value to pass it to the Liquibase API.

{
   "hints": [
    {
   
        "name": "spring.liquibase.change-log",
        "providers": [
            {
   
                "name": "handle-as",
                "parameters": {
   
                    "target": "org.springframework.core.io.Resource"
                }
            }
        ]
    }
]}

Logger Name

The logger-name provider auto-completes valid logger names and logger groups. Typically, package and class names available in the current project can be auto-completed. If groups are enabled (default) and if a custom logger group is identified in the configuration, auto-completion for it should be provided. Specific frameworks may have extra magic logger names that can be supported as well.

This provider supports the following parameters:
Parameter Type Default value Description

group

boolean

true

Specify whether known groups should be considered.

Since a logger name can be any arbitrary name, this provider should allow any value but could highlight valid package and class names that are not available in the project’s classpath.

The following metadata snippet corresponds to the standard logging.level property. Keys are logger names, and values correspond to the standard log levels or any custom level. As Spring Boot defines a few logger groups out-of-the-box, dedicated value hints have been added for those.

{
   "hints": [
    {
   
        "name": "logging.level.keys",
        "values": [
            {
   
                "value": "root",
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值