Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure the prompt function in SpringBoot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to configure the prompt function of SpringBoot. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Purpose

The auxiliary function of configuring automatic prompts can make the configuration write faster and improve the accuracy greatly.

Springboot jar contains metadata files that provide details of all supported configuration properties. The purpose of the file is to enable IDE developers to provide contextual help and code completion when users use application.properties or application.yml files. Most metadata files are automatically generated at compile time by processing all items annotated with @ ConfigurationProperties. You can also write part of the metadata manually.

Version

Refer to SpringBoot 2.2.0.RELEASE documentation

File

META-INF/spring-configuration-metadata.json (automatically generated) or META-INF/additional-spring-configuration-metadata.json (manually added) in the jar package

Actual combat

Org.springframework.boot spring-boot-configuration-processor true@Configuration@ConfigurationProperties (prefix = "file.upload") public class FileUploadConfig {/ * * Maximum number of bytes per file * / private String maxSize = "1024M"; / * * disallowed file suffix * / private String rejectSuffix / / Note: you must have getter/setter when using it, otherwise the prompt corresponding to this attribute will not be automatically generated / / getter/setter} @ Configuration@ConfigurationProperties ("map.test") public class MapTestConfig {/ * * hint for testing Map type data * / private Map data will be omitted here for space reasons. / / Note: you must have getter/setter when using it, otherwise the prompt corresponding to this attribute will not be automatically generated / / getter/setter} will be omitted here because of the space.

Chinese comments will be garbled. For the above intentional comments in Chinese, the corresponding description will be specified in the following file to see if it will be overwritten.

Additional-spring-configuration-metadata.json {"properties": [{"name": "file.upload.reject-suffix", "type": "java.lang.String", "defaultValue": "exe,jar", "description": "The file suffix is not allowed.", "sourceType": "com.lw.metadata.config.FileUploadConfig"}, {"name": "map.test.data", "type": "java.util.Map" "description": "Tips for testing Map type data.", "sourceType": "com.lw.metadata.config.MapTestConfig"}], "hints": [{"name": "map.test.data.keys", "values": [{"value": "name", "description": "The name of the person."}, {"value": "sex" "description": "The sex of the person."}]}}

After maven compile, the generated additional-spring-configuration-metadata.json is the same as in the source code, and the generated spring-configuration-metadata.json is as follows:

{"groups": [{"name": "file.upload", "type": "com.lw.metadata.config.FileUploadConfig", "sourceType": "com.lw.metadata.config.FileUploadConfig"}, {"name": "map.test", "type": "com.lw.metadata.config.MapTestConfig", "sourceType": "com.lw.metadata.config.MapTestConfig"}] "properties": [{"name": "file.upload.max-size", "type": "java.lang.String", "description": "Maximum number of bytes per file", "sourceType": "com.lw.metadata.config.FileUploadConfig", "defaultValue": "1024m"}, {"name": "file.upload.reject-suffix", "type": "java.lang.String", "description": "The file suffix is not allowed." "sourceType": "com.lw.metadata.config.FileUploadConfig", "defaultValue": "exe,jar", {"name": "map.test.data", "type": "java.util.Map", "description": "Tips for testing Map type data.", "sourceType": "com.lw.metadata.config.MapTestConfig"}], "hints": [{"name": "map.test.data.keys" "values": [{"value": "name", "description": "The name of the person."}, {"value": "sex", "description": "The sex of the person."}]}

Effect.

From this, we can see the following phenomena:

The default values in the code will be automatically generated to the prompt file, such as: comments in the FileUploadConfig#maxSize code will be automatically generated in the prompt file, such as: the prompt in the FileUploadConfig#maxSize additional-spring-configuration-metadata.json file will override the automatically generated corresponding attribute, if the automatic generation does not have this attribute, it will be automatically added.

Write the prompt file manually

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. "]}]}

Groups

Grouping, grouping configuration classes.

Can be grouped by file, that is, all properties of the same profile are placed in the same group

The full name of the name String Y grouping the class name of the type String N grouping data type (for example, the full class name using the @ ConfigurationProperties annotation, the return type using the @ Bean annotation), a short description of the description String N grouping. SourceType String N provides the class name of the grouping source. SourceMethod String N provides grouping methods, including parentheses and parameter types.

Properties

Prompt subject, must

The full name of the name String Y property. The name is in a lowercase period-separated format, such as the full signature of the server.address type String N attribute data type (such as: java.lang.String) or the complete generic type (such as: java.util.Map). This property prompts the user for a worthwhile type. Native types use their wrapper types here (for example, boolean uses java.lang.Boolean). A short description of the description String N grouping. SourceType String N provides the class name of the grouping source. DefaultValue Object N default value. Used when the property is specified. Deprecation Deprecation N specifies whether the property is deprecated.

The deprecation attribute is as follows:

Level String N deprecation level, which can be warning (default) or error. Warning: the attribute should still be available; the error: attribute does not guarantee a short reason why the reason String N attribute can be deprecated. Replacement String N replaces the full name of the new property for this deprecated property. Nullable

Note: prior to Spring Boot 1.3, deprecated of type boolean was used.

The following example, from official documentation, shows how to handle this scenario:

@ 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);}}

Whether the attribute type must be used for

Once the getTarget and setTarget methods are removed from the public API, the automatic deprecation prompt in the metadata also disappears. If you want to keep the prompt, adding manual metadata with the error deprecation level ensures that the user still knows about the attribute. This is particularly useful when providing alternatives.

Hints

Auxiliary hint, not required

Name String Y prompts for the full name of the attribute associated with it. The name is in a lowercase period-separated format (such as: spring.mvc.servlet.path), and if the attribute is associated with a map type (such as: system.contexts), you are prompted to associate the key (system.contexts.keys) or value (system.contexts.values) of the map. Collection of values ValueHint [] N valid values. (detailed in the following table) the providers ValueProvider [] N provider collection. (detailed in the table below)

The values attribute is as follows:

@ ConfigurationProperties ("sample") public class SampleProperties {private Map contexts; / / getters and setters} {"hints": [{"name": "sample.contexts.keys", "values": [{"value": "sample1"}, {"value": "sample2"}]}]}

Whether the attribute type must be used for

The hint is a hint for each pair of key-value in the Map.

The .keys and .values prefixes must be associated with the keys and values of the Map, respectively.

The providers attribute is as follows:

The name of the name String N that is used to provide additional content help for the element referenced by the prompt. Any other parameters supported by parameters JSON object N provider (see the documentation for provider for more information).

ValueProvider

It is generally not needed. It is recommended to skip it.

The following table summarizes the list of supported providers:

Any allows you to provide any added value. Class-reference automatically completes the classes available in the project. A base class constraint that is usually specified by the target parameter. Handle-as handles the property as if it were defined by a type defined by the required target parameter. Logger-name automatically completes a valid logger name and logger group. Typically, the package and class names available in the current project can be completed automatically, or groups can be defined. Spring-bean-reference automatically completes the bean names available in the current project. A base class constraint that is usually specified by the target parameter. Spring-profile-name automatically completes the name of the spring profile available in the project.

Any

All values that match the property type.

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

Whether the attribute type must use the property description

The following parameters are provided:

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

Handle-as

Allows you to replace the type of a property with a more advanced type.

This usually occurs when the property has a java.lang.String type, because you do not want the configuration class to depend on a class that is not on the classpath.

Target String (Class) No Y is the fully qualified name of the type considered by the attribute.

The available values are as follows:

Any java.lang.Enum: lists the possible values of the attribute.

Java.nio.charset.Charset: supports automatic completion of character sets / coding values (e.g. utf-8)

Java.util.Locale: automatically completes the locale (e.g. en_US)

Org.springframework.util.MimeType: supports auto-completion of content-type values (e.g. text/plain)

Org.springframework.core.io.Resource: supports automatic resource abstraction of spring to reference files on the file system or classpath (such as:

Classpath:/sample.properties)

Note: if you want to provide more than one value, use Collection or array type

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

Parameter type default value

Description

Logger-name

Logger-name provider automatically completes a valid logger name and logger group. Typically, the package and class names available in the current project can be completed automatically. If the group is enabled (default) and a custom logger group is identified in the configuration, autocomplete for that group should be provided.

The following parameters are supported:

Group boolean true specifies whether known groups should be considered.

Because the logger name can be any name, this provider should allow any value, but can highlight valid packages and class names that are not available in the classpath of the project.

The following are the logging.level properties. Keys is the logger name, and values is associated with the standard log levels or custom level

{"hints": [{"name": "logging.level.keys", "values": [{"value": "root", "description": "Root logger used to assign the default logging level."}, {"value": "sql", "description": "SQL logging group including Hibernate SQL logger."}, {"value": "web", "description": "Web logging group including codecs."}] "providers": [{"name": "logger-name"}]}, {"name": "logging.level.values", "values": [{"value": "trace"}, {"value": "debug"}, {"value": "info"}, {"value": "warn"}, {"value": "error"} {"value": "fatal"}, {"value": "off"}], "providers": [{"name": "any"}]}]}

Parameter type default value description

Spring-bean-reference

This provider automatically completes the bean defined in the configuration of the current project. The following parameters are supported:

Target String (Class) has no fully qualified name of the bean class that should be assigned to the candidate. It is commonly used to screen non-candidate bean.

The following example indicates that the spring.jmx.server property defines the use of MBeanServer

{"hints": [{"name": "spring.jmx.server", "providers": [{"name": "spring-bean-reference", "parameters": {"target": "javax.management.MBeanServer"}}]}]}

Parameter type default value description

Spring-profile-name

This provider automatically completes the spring configuration file defined in the configuration of the current project.

The following example indicates the name of the profile that can be enabled by the spring.profiles.active property.

{"hints": [{"name": "spring.profiles.active", "providers": [{"name": "spring-profile-name"}]}]}

Repeatable metadata items

Objects with the same "property" and "group" names can appear multiple times in a metadata file. For example, you can bind two separate classes to the same prefix, and each class has property names that may overlap. Although the same name that appears multiple times in metadata should not be common, users of metadata should be careful to ensure that they support the name.

Automatically generate prompt files

By using spring-boot-configuration-processor jar, you can easily generate your own configuration metadata files from classes annotated with @ ConfigurationProperties. Jar includes an java comment handler that is called when the project is compiled. With this processor, you need to introduce spring-boot-configuration-processor dependencies.

Org.springframework.boot spring-boot-configuration-processor true

The processor gets the classes and methods annotated with @ configurationproperties. The javadoc of the field value in the configuration class is used to populate the description property.

Note: you should only use simple text with the @ originationproperties field javadoc, as they are not processed until they are added to the json.

If the class has a constructor with at least one parameter, create a property for each constructor parameter. Otherwise, properties are discovered through standard getter and setter, which have special treatment for collection types (even if only getter exists).

The annotation processor also supports lombok annotations using @ data, @ getter, and @ setter.

The annotation processor cannot automatically detect the default values for Enum and Collections. Manual metadata should be provided in cases where a collection or enumeration property has a non-empty default value.

ConfigurationProperties (prefix= "acme.messaging") public class MessagingProperties {private List addresses = new ArrayList (Arrays.asList ("a", "b")); private ContainerType = ContainerType.SIMPLE; / /. Getter and setters public enum ContainerType {SIMPLE, DIRECT}}

To prompt for the default values of the above attributes, you should manually add metadata such as the following:

{"properties": [{"name": "acme.messaging.addresses", "defaultValue": ["a", "b"]}, {"name": "acme.messaging.container-type", "defaultValue": "simple"}]}

Note: if you use AspectJ in your project, you need to make sure that the annotation processor runs only once. When using Maven, you can explicitly configure the maven-apt-plugin plug-in and add dependencies to the annotation processor only there. You can also have the AspectJ plug-in run on all processes and disable annotation processing in maven-compiler-plugin 's configuration, as follows:

Org.apache.maven.plugins maven-compiler-plugin none

Bind attribute

The annotation processor automatically treats inner classes as nested attributes.

ConfigurationProperties (prefix= "server") public class ServerProperties {private String name; private Host host; / /. Getter and setters public static class Host {private String ip; private int port; / /... Getter and setters}}

The above example generates metadata information for the server.name, server.host.ip, and server.host.port properties. You can use the @ NestedconfigurationProperty annotation on the field to indicate that regular (non-internal) classes should be treated as nested classes.

Note: this has no effect on collections and mappings because these types are automatically identified and a metadata attribute is generated for each type.

Add additional metadata

Spring Boot's configuration file handling is very flexible, and in general, there may be properties that are not bound to @ ConfigurationProperties bean. You may also need to adjust some properties of the existing key, and to support this and allow you to provide custom "prompts", the annotation processor automatically merges the prompts in the META-INF/additional-spring-configuration-metadata.json into the main metadata file (spring-configuration-metadata.json).

If you reference an attribute that has been automatically detected, the description, default value, and deprecation information, if specified, are overwritten. If the declaration in the manual property is not identified in the current module, it is added as a new property.

The format of the additional-spring-configuration-metadata.json file is the same as the spring-configuration-metadata.json file. Additional properties files are optional. Do not add files if you do not have any other attributes.

This is the end of this article on "how to configure the prompt function of SpringBoot". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report