In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
The principle and core notes of Spring Boot automatic configuration and how to use automatic configuration to implement custom Starter components. In view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
Excerpt: reading is to finish reading these words, but also to think carefully, to write a book is the same, to do everything the same.
Figure 2 Chapter 2 Catalog structure Diagram
Spring Boot configuration
Spring Boot configuration, including automatic configuration and externalized configuration. This chapter first implements the custom property project, externalizes the attribute configuration in the application.properties application configuration file, and then obtains the property value in the project. Then we will describe in detail how to obtain properties, externalized configuration and automatic configuration. Finally, we will introduce the use of automatic configuration of custom Start components.
2.1 Quick start Project
In the HelloBookController control layer of the first chapter, strings are used to represent book information in hard-coded code. Below, the information of the book is externalized and configured in application.properties as attributes. The advantage is that the application parameters, business parameters or third-party parameters are uniformly configured in the application configuration file, so as to avoid configuration intrusion into the business code, achieve a configurable way, and facilitate timely adjustment and modification.
2.1.1 configuration Properties
The new project is named chapter-2-spring-boot-config. Configure the book title and author in application.properties as follows:
# # Book Information demo.book.name= [Spring Boot 2.x Core Action] demo.book.writer=BYSocket
Each line of parameters in the .properties file is stored as a pair of strings, one storage parameter name, called the key, and the other as the value. Commonly referred to as key-value pair configuration. The pound sign (#) or the exclamation point (!) in the English state indicates that the text of the first line is a comment as the first non-empty character in the first line. In addition, the backslash (\) is used to escape characters.
Spring Boot supports and recommends using the configuration file in YAML format. Replace the application.properties file with the application.yml file and configure the same attributes as follows:
# # Book Information demo: book: name: "Spring Boot 2.x Core Technology practice-the Foundation" writer: bricklayer BYSocket
YAML is a highly readable format used to express data sequences. When representing the format of key-value pairs, note that the key and value are separated by colons and white space characters. To emphasize, whitespace characters are required, and IDE generally prompts you. Both configurations are very convenient, choose .properties or .yml file configuration in development. However, if both configuration files exist at the same time, the .properties configuration file is preferred by default. The comparison between YAML and .properties configuration file is shown in figure 2-1:
Figure 2-1 comparison of YAML and .properties configuration files
Note:
When configuring Chinese values in application.properties, there will be garbled characters when reading. Because the default encoding of the Java .properties file is iso-8859, and the Spring Boot application is read in the UTF-8 encoding mode, this leads to garbled problems.
The workaround in the official Issue is to escape the Chinese values configured in the .properties file into Unicode-encoded form. For example, the demo.book.writer= bricklayer should be configured as demo.book.writer=\ u6ce5\ u74e6\ u5320. Escape quickly by using IDEA properties plug-in or Java file transcoding tool native2ascii. The tool is implemented online at the following address: https://javawind.net/tools/native2ascii.jsp
2.1.2 create an attribute class
Create a new package directory demo.springboot.config in the project, and create an attribute class named BookProperties in the directory, as follows:
Import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;/** * Book attribute * / @ Componentpublic class BookProperties {/ * title * / @ Value ("${demo.book.name}") private String name; / * author * / @ Value ("${demo.book.writer}") private String writer; / /. Omit getter / setter method}
The property Bean of the book is defined with the @ Component annotation, and the attribute values of the application.properties file are automatically injected into the member variables (or method parameters) of the Bean through the @ Value annotation. The @ Value annotation refers to an attribute in the form of "${propName}", and propName represents the name of the attribute.
Knowledge points of the core notes:
@ Component Note: @ Component marks the class and generally refers to the component Bean. When the application starts, it will be loaded by the container and added to the container management. The common @ Controller, @ Service, and @ Repository are the classified components of @ Component, corresponding to the Bean of the control layer, the service layer, and the persistence layer, respectively.
@ Value comment: @ Value marks the field or method parameter of Bean and is responsible for setting the default property value for the field or method parameter based on the expression. The usual format is annotation + SpEL expression, such as @ Value ("SpEL expression").
When using the @ Vlaue annotation to reference attribute values, make sure that the referenced attribute values exist in the application.properties file and match, otherwise it will cause an error in the creation of Bean and throw an illegal parameter exception of java.lang.IllegalArgumentException.
2.1.3 get attributes
Modify the original HelloBookController class, get the book property Bean by injection and return it. The code is as follows:
Import demo.springboot.config.BookProperties;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloBookController {@ Autowired BookProperties bookProperties; @ GetMapping ("/ book/hello") public String sayHello () {return "Hello," + bookProperties.getWriter () + "is writing" + bookProperties.getName () + "!" ;}}
With the @ Autowired annotation marked in the BookProperties field, the control layer automatically assembles the attribute Bean and uses it. By default, the annotated Bean must exist, the NULL value needs to be allowed, and its required property can be set to false: @ Autowired (required = false).
2.1.4 run the project
Execute the ConfigApplication class startup, and after the console sees the output that runs successfully, open the browser access / book/hello address, and you can see the returned result as shown in figure 2-2:
Figure 2-2 Hello Book page
You can also verify whether the property acquisition is successful by means of unit tests, which are described in Chapter 9. The unit test code is as follows:
Import demo.springboot.config.BookProperties;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@RunWith (SpringRunner.class) @ SpringBootTestpublic class ConfigApplicationTests {@ Autowired BookProperties bookProperties @ Test public void testBookProperties () {Assert.assertEquals (bookProperties.getName (), "'Spring Boot 2.x Core Action'"); Assert.assertEquals (bookProperties.getWriter (), "BYSocket");}} 2.2 configure how to get attributes
There are two common ways to obtain configuration properties based on @ Value and @ ConfigurationProperties annotations. The two methods are suitable for different scenarios. The following details describe their usage and scenarios.
2.2.1 @ Value Annotation
The @ Value annotation annotates variables or method parameters of Bean and is responsible for setting default property values for field or method parameters based on expressions. The usual format is annotation + SpEL expression, such as @ Value ("SpEL expression"), and annotated above the corresponding field or method, and variables must be annotated one by one. This approach is suitable for small and uncomplex attribute structures. When the attribute structure is complex and there are many fields, this approach will be cumbersome, and you should consider using the @ ConfigurationProperties annotation.
In addition, other .properties files for the corresponding path are introduced through the @ PropertySource annotation. After reconfiguring the book information to the new book.properties configuration file under classpath, the code to read the new configuration file is as follows:
Import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;/** * Book attribute * / @ Component@PropertySource ("classpath:book.properties") public class BookProperties {/ * title * / @ Value ("${demo.book.name}") private String name / * * author * / @ Value ("${demo.book.writer}") private String writer; / /. Omit the getters / setters method} 2.2.2 @ ConfigurationProperties annotation
Create a property class named BookComponent in the package directory demo.springboot.config, and use the @ ConfigurationProperties annotation to get the properties, as follows:
Import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** * Book attribute * * / @ Component@ConfigurationProperties (prefix = "demo.book") public class BookComponent {/ * * title * / private String name; / * * author * / private String writer; / /. Omit getters / setters method}
Similar to the @ Value annotation, using @ ConfigurationProperties (prefix = "demo.book") annotations above the class can achieve the same effect. The prefix of the @ ConfigurationProperties annotation is the parameter name of the specified property. Matches the properties of the "demo.book.*" structure in the configuration file, and the asterisk "*" refers to the field names that match the BookComponent class one by one. For example, the field name represents the title of the book and matches the value of the demo.book.name attribute.
The @ Value annotation method forces the fields to correspond to the configuration file, while the @ ConfigurationProperties annotation method is not required. In general, all fields should be guaranteed to correspond one to one in the configuration file. If there is no corresponding attribute value, the field is empty by default, and the @ ConfigurationProperties annotation method will not throw any exception. Spring Boot recommends using the @ ConfigurationProperties annotation method to get the attribute.
Unit tests are also used to verify that the property acquisition was successful. The unit test code is as follows:
@ AutowiredBookComponent bookComponent;@Testpublic void testBookComponent () {Assert.assertEquals (bookComponent.getName (), "'Spring Boot 2.x Core Action'"); Assert.assertEquals (bookComponent.getWriter (), "BYSocket");} API org.springframework.boot.context.properties.ConfigurationProperties annotation parameters
Prefix string value, the property object that binds the name prefix.
Value string value, which is the same as the prefix parameter.
IgnoreInvalidFields Boolean value, default false. Invalid fields are ignored when binding objects.
IgnoreUnknownFields Boolean value, default true. Unknown fields are ignored when binding objects.
2.2.3 @ ConfigurationProperties data validation
The @ ConfigurationProperties annotation method supports verification, that is, when an attribute class is annotated by the @ Validated annotation, Spring Boot will validate the fields of the class when it is initialized. Add JSR-303 constraint annotations to the fields of the class for data validation. The following is to add non-NULL and string non-null constraints to the book attribute field, as follows:
Import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import org.springframework.validation.annotation.Validated;import javax.validation.constraints.NotEmpty;import javax.validation.constraints.NotNull;/** * Book attribute * * / @ Component@ConfigurationProperties (prefix = "demo.book") @ Validatedpublic class BookComponent {/ * title * / @ NotEmpty private String name / * * author * / @ NotNull private String writer; / /. Omit getters / setters method}
Enable data validation for BookComponent fields with the @ Validated annotation. If the name field is NULL or an empty string, an BindValidationException binding data verification exception will be thrown. Data validation is commonly used in mailbox format or property fields with length restrictions. In addition, to validate the value of a nested property, you must mark the @ Valid annotation above the nested object field to trigger its validation. For example, if you add a nested object publisher Publishing to the book property, you need to mark the @ Valid annotation above the object to turn on the data validation of the Publishing object. To sum up, the two methods of attribute acquisition have their own advantages and disadvantages, as shown in figure 2-3:
Figure 2-3 @ ConfigurationPropertiesd vs @ Value
2.3 externalized configuration
Spring Boot can externalize the configuration, that is, separate storage outside the classpath, a mode called "externalized configuration". It is often used in different environments to separate the configuration from the external code. As long as you simply modify the externalized configuration, you can still run the same application code. Externalizing the configuration is not only in the form of .properties and .yml property files, but can also be implemented using environment variables and command-line arguments. So how does Spring Boot control conflicts in externalized configurations when the same properties are configured in multiple places? The answer is to externalize configuration priorities.
2.3.1 externalize configuration priority
It is easy to override the .properties file configuration with a command line configuration. Normally, use the Java command to run the project. The code is as follows:
/ / run java-jar target/chapter-2-spring-boot-config-1.0.jar under the chapter-2-spring-boot-config directory
Below, change the author information of the book from BYSocket to Jeff, and override the attribute through command line configuration. The code is as follows:
Java-jar target/chapter-2-spring-boot-config-1.0.jar-- demo.book.writer=Jeff
In a command line configuration, property values are formatted with two consecutive minus signs to mark the attribute. After seeing the output that runs successfully on the console, open a browser and visit the / book/hello address, and you can see the return result shown in figure 2-4:
Figure 2-4 Book information is overwritten page
The command line configuration overlay attribute provides great function and convenience. It is common to modify the configuration of the project when running the project with shell script.
But this raises a question: doesn't it make the project very intrusive? if you open this function, it will lead to unknown security problems. Therefore, Spring Boot provides masking command line attribute value settings, and sets the setAddCommandLineProperties method to false in the application startup class, which is used to disable the command line configuration feature. The code is as follows:
SpringApplication.setAddCommandLineProperties (false)
The priority of the command line configuration property is the fourth. When externalizing the configuration to get properties, it is obtained from the highest to the lowest priority. If an attribute exists in the high priority, the attribute is returned and the low priority attribute is ignored. The priorities are as follows:
Local Devtools global configuration
@ TestPropertySource annotation configuration during testing
Properties configuration of @ SpringBootTest annotations during testing
Command line configuration
SPRING_APPLICATION_JSON configuration
ServletConfig initialization parameter configuration
ServletContext initialization parameter configuration
JNDI parameter configuration for Java environment
Property configuration of Java system
OS environment variable configuration
RandomValuePropertySource configuration with random attributes only
Multi-environment configuration file outside the project jar (application- {profile} .properties or YAML)
Multi-environment configuration file (application- {profile} .properties or YAML) within the project jar
Application profile (application.properties or YAML) other than the project jar
Application profile (application.properties or YAML) within the project jar
@ PropertySource annotation configuration in @ Configuration class
Default property configuration (specified by SpringApplication.setDefaultProperties)
2.3.2 attribute reference
When configuring properties in application.properties, other properties can be referenced directly between properties in the form of "${propName}". For example, the description attribute of the description of the new book is as follows:
# # Book Information demo.book.name= [Spring Boot 2.x Core Action] demo.book.writer=BYSocketdemo.book.description=$ {demo.book.writer}'s ${demo.book.name}
The demo.book.description attribute refers to the demo.book.name and demo.book.writer properties defined earlier, and its value is BYSocket's [Spring Boot 2.x Core Action]. On the one hand, the same configuration can be reused, on the other hand, the readability of the configuration is enhanced.
2.3.3 use random numbers
When configuring properties in application.properties, you can use random number configurations, such as injecting certain keys, UUID, or test cases, which need not to be a fixed value at a time. The RandomValuePropertySource class randomly provides an integer, a long integer, a UUID, or a string. The usage code is as follows:
My.secret=$ {random.value} my.number=$ {random.int} my.bignumber=$ {random.long} my.uuid=$ {random.uuid} my.number.less.than.ten=$ {random.int (10)} my.number.in.range=$ {random.int [1024May65536]} 2.3.4 Multi-environment configuration
Multi-environment means that production servers with different configurations are deployed using the same engineering code, such as development environment, test environment, pre-release environment, production environment and so on. The project port, database configuration, Redis configuration and log configuration of each environment will be different. In the traditional mode, the configuration needs to be modified, the project is recompiled and packaged, and deployed to the specified environment server. As a result, configuration errors are prone to occur, resulting in inefficient development and deployment. Spring Boot uses multi-context configurations to solve this problem.
Multi-environment configuration, similar to the idea of building configuration files in Maven, that is, configure configuration files for multiple different environments, and then specify the properties to read specific configuration files through the spring.profiles.active command. Multi-context profiles are different from application.properties application profiles. The convention naming format for multi-environment configuration files is application- {profile} .properties. The multi-context configuration feature defaults to activation, and if other configurations are not activated, {profile} defaults to default, the application-default.properties default configuration file will be loaded, and the application.properties application configuration file will be loaded without it.
The properties of the multi-environment profile are read in the same way as from the application.properties application configuration file. Regardless of whether the multi-environment configuration files are in or out of the project jar package, overwrite other configuration files according to the configuration priority. In the development of micro-service practices, a similar deploy project is often used to manage configuration files and package other business projects.
In the application.properties sibling directory, create a new application-dev.properties as the development environment configuration file, and configure it as follows:
# # Book Information demo.book.name= [Spring Boot 2.x Core Action] From Devdemo.book.writer=BYSocket
Create a new application-prod.properties as the production environment configuration file, as shown below:
# # Book Information demo.book.name= From Proddemo.book.writer=BYSocket
Specify to read the dev environment configuration file and run the project through the command line, as follows:
Java-jar target/chapter-2-spring-boot-config-1.0.jar-- spring.profiles.active=dev
In multiple environment configurations, use the command-spring.profiles.active=dev to specify to read a configuration file, change dev to prod, and easily switch to read the configuration of the production environment. You can also confirm in the log of the console that the configuration reads from dev:
2017-11-09 12 demo.springboot.ConfigApplication 1015 52.978 INFO 72450-[main] demo.springboot.ConfigApplication: The following profiles are active: dev
Finally, open the browser, visit the / book/hello address, and you can see the returned result as shown in figure 2-5:
Figure 2-5 dev Environment Book Information Page
2.4 automatic configuration
The Spring Boot spring-boot-autoconfigure dependency implements the default configuration item, that is, applying the default value. This mode is called "autoconfiguration". Spring Boot auto-configuration automatically loads dependency-related configuration properties and starts dependencies based on the added dependencies. For example, the default built-in container is Tomcat, and the port is set to 8080 by default.
Why do I need automatic configuration? As the name implies, the meaning of automatic configuration is to take advantage of this mode instead of configuring XML tedious mode. In the past, using Spring MVC, you need to configure component scanning, scheduler, view parser, and so on. After using Spring Boot automatic configuration, you only need to add MVC components to automatically configure the required Bean. All implementations of automatic configuration are in spring-boot-autoconfigure dependencies, including automatic configuration of Spring MVC, Data, and other frameworks.
2.4.1 spring-boot-autoconfigure dependency
Spring-boot-autoconfigure dependency is the core Starter component that Spring Boot implements automatic configuration. In fact, the structure of the source code packet is shown in figure 2-6:
Figure 2-6 spring-boot-autoconfigure dependency package directory
As you can see from the figure, the common core packages are as follows:
Org.springframework.boot.autoconfigureorg.springframework.boot.autoconfigure.data.jpaorg.springframework.boot.autoconfigure.thymeleaforg.springframework.boot.autoconfigure.web.servletorg.springframework.boot.autoconfigure.web.reactive... Omit
There is a corresponding automatic configuration class under the respective package directory, as follows:
JpaRepositoriesAutoConfiguration ThymeleafAutoConfigurationWebMvcAutoConfigurationWebFluxAutoConfiguration... Omit
The above automatic configuration classes are Jpa automatic configuration class, Thymeleaf automatic configuration class, Web MVC automatic configuration class and WebFlux automatic configuration class. The use of the WebFlux responsive framework is described in detail in Chapter 3.
The responsibility of spring-boot-autoconfigure is to scan the ClassPath directory for automatic configuration of class corresponding dependencies through the @ EnableAutoConfiguration core annotation, obtain the default configuration according to certain rules, and automatically initialize the required Bean. You can also modify the default configuration items in the application.properties configuration file. The common configuration list addresses are as follows:
Https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
2.4.2 @ EnableAutoConfiguration Annotation
The automatic configuration working mechanism is implemented through the AutoConfigurationImportSelector automatic configuration import selector class of @ Import in the @ EnableAutoConfiguration annotation. The specific process for consulting the source code is as follows:
AutoConfigurationImportSelector reads the META-INF/spring.factories file under the ClassPath directory through the SpringFactoriesLoader.loadFactoryNames () core method.
Spring Boot autoconfiguration classes configured in the spring.factories file, such as the common WebMvcAutoConfiguration Web MVC autoconfiguration classes and ServletWebServerFactoryAutoConfiguration container autoconfiguration classes.
Both the spring.factories file and the application.properties file belong to the configuration file and are configured in the format of key-value pairs. Each automatic configuration class configured in it defines the instance configuration of the relevant Bean, as well as the conditions under which automatic configuration and which Bean are instantiated.
When pom.xml adds a Starter dependency component, the default configuration for that dependency is automatically triggered.
For example, after adding a spring-boot-starter-web dependency, launching the application will trigger the container to automatically configure the class. Part of the code of the container auto-configuration class ServletWebServerFactoryAutoConfiguration is as follows:
Package org.springframework.boot.autoconfigure.web.servlet;@Configuration@ConditionalOnClass ({ServletRequest.class}) @ ConditionalOnWebApplication (type = Type.SERVLET) @ EnableConfigurationProperties ({ServerProperties.class}) @ Import ({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class}) public class ServletWebServerFactoryAutoConfiguration {... Omit}
In the above code, the @ ConditionalOnClass annotation indicates that the corresponding ServletRequest class exists under the ClassPath directory, and the @ ConditionalOnWebApplication annotation indicates that the application is a Servlet Web application, and the container auto-configuration is started only when the @ ConditionalOnWebApplication annotation indicates that the application is an Servlet Web application, and the port is set to 8080 by default through the ServerProperties class. The Type.SERVLET enumeration represents Servlet Web applications, and the Type.REACTIVE enumeration represents responsive WebFlux applications.
Automatic configuration is a double-edged sword. If you use it well, it's like the martial arts in the world can only be broken quickly. However, pay attention to some problems caused by automated configuration. Common problems are:
The Spring Boot project adds some Starter component dependencies without triggering component automatic configuration
When Spring Boot configures multiple different data source configurations, it uses XML to configure multiple data sources, but its default data source configuration triggers problems with automatic configuration.
In similar scenarios, the solution is to specify and exclude automatic configuration classes through the exclude attribute, as shown in the following code:
@ SpringBootApplication (exclude = {DataSourceAutoConfiguration.class})
It is also equivalent to configuring @ EnableAutoConfiguration annotation. The code is as follows:
@ SpringBootApplication@EnableAutoConfiguration (exclude = {DataSourceAutoConfiguration.class})
Automatic configuration is the most intelligent. Only when the exclude attribute is configured, Spring Boot first initializes the user-defined Bean, and then automatically configures it.
2.4.3 using automatic configuration of custom Starter components
When companies need to share or open source Spring Boot Starter component dependencies, they can take advantage of automatic configuration of custom Starter components. A complete Starter component includes the following two points:
An automatic configuration module that provides automatic configuration function.
A component module that provides dependency management functions, that is, it encapsulates all the functions of the component and is used immediately out of the box.
The implementation of custom Starter components does not make a strict distinction between the two, but can be implemented by combining automatic configuration with dependency management. The following uses automatic configuration to implement custom Starter components: the spring-boot-starter-swagger component is used to quickly generate API documents and simplify the native use of Swagger2.
The spring-boot-starter-swagger component is an open source project of the Spring For All Community (spring4all.com) and the source code address is https://github.com/SpringForAll/spring-boot-starter-swagger.
What is Swagger2?
Swagger2 is the largest development framework of API, based on the OpenAPI specification (OAS), which manages the entire life cycle of API, that is, from API design to documentation, from testing to deployment. For more information, see its website, https://swagger.io.
Spring-boot-starter-swagger component dependency
Create a new Spring Boot project named spring-boot-starter-swagger. Configure relevant in pom.xml
Org.springframework.boot spring-boot-starter true org.springframework.boot spring-boot-configuration-processor true io.springfox springfox-swagger-ui ${version.swagger} io.springfox springfox-swagger2 ${version.swagger} io.springfox springfox-bean-validators ${version.swagger} org.projectlombok lombok 1.16.12 provided
The spring-boot-starter component dependency is added to the configuration for automatic configuration features, and the springfox-swagger2 dependency is the Swagger2 framework.
Swagger2 attribute configuration class SwaggerProperties
Create a new SwaggerProperties Swagger2 property configuration class that contains all default property values. When using this component, you can configure the corresponding property items in the application.properties configuration file to override the default configuration. The code is as follows:
Import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.boot.context.properties.ConfigurationProperties;import springfox.documentation.schema.ModelRef;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;@Data@ConfigurationProperties ("swagger") public class SwaggerProperties {/ * whether to enable swagger**/ private Boolean enabled; / * * title * * / private String title = ""; / * * description * * / private String description = "" / * * version * * / private String version = ""; / * * license * * / private String license = ""; / * * license URL**/ private String licenseUrl = ""; / * * terms of Service URL**/ private String termsOfServiceUrl = ""; private Contact contact = new Contact (); / * * package path that swagger will resolve * * / private String basePackage = "" / * * url rules that swagger will parse * * / private List basePath = new ArrayList (); / * * url rules that need to be excluded on the basis of basePath * * / private List excludePath = new ArrayList (); / * * grouping documents * * / private Map docket = new LinkedHashMap (); / * host information * / private String host = ""; / * global parameter configuration * * / private List globalOperationParameters;. Omitted. For more information, please see GitHub}
Use @ ConfigurationProperties (prefix = "swagger") to mark the name of the parameter with the specified attribute above the class as swagger. Properties that match to the "swagger.*" structure in the configuration file, for example, the field title title represents the title, matches the value of the swagger.title attribute.
Swagger2 automatic configuration class SwaggerAutoConfiguration
Create a new class called SwaggerAutoConfiguration Swagger2 automatic configuration, which provides Swagger2 dependency management and automatic configuration functions. The code is as follows:
Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;@Configuration@ConditionalOnProperty (name = "swagger.enabled", matchIfMissing = true) @ Import ({Swagger2DocumentationConfiguration.class, BeanValidatorPluginsConfiguration.class}) public class SwaggerAutoConfiguration implements BeanFactoryAware {private BeanFactory beanFactory Bean @ ConditionalOnMissingBean public SwaggerProperties swaggerProperties () {return new SwaggerProperties ();} @ Bean @ ConditionalOnMissingBean @ ConditionalOnProperty (name = "swagger.enabled", matchIfMissing = true) public List createRestApi (SwaggerProperties swaggerProperties) {. Omitted. For more information, please see GitHub} @ Override public void setBeanFactory (BeanFactory beanFactory) throws BeansException {this.beanFactory = beanFactory;}}
The implementation process of the above code is as follows:
The @ Configuration annotation is annotated at the top of the class, indicating that it is a configuration class.
The @ Import annotation introduces the configuration class Swagger2DocumentationConfiguration provided by Swagger2 and the Bean data validation plug-in configuration class BeanValidatorPluginsConfiguration.
The @ ConditionalOnMissingBean annotation annotates two methods, and the annotated initialization method is executed when the Bean is not created. The first tagged method is swaggerProperties (), which is used to instantiate the attribute configuration class SwaggerProperties;. The second tagged method is createRestApi (), which is used to instantiate the Docket list object of the Swagger2 API map.
@ ConditionalOnProperty is annotated in the createRestApi () method, and the name property checks the environment configuration item swagger.enabled. By default, this initialization method is triggered if the property exists and is not a false. The default value of the matchIfMissing property is false, which is set to true, which means that if the environment configuration item is not set, it will also be triggered.
Swagger2 starts the annotation class EnableSwagger2Doc
Create a new EnableSwagger2Doc Swagger2 startup annotation class to switch on and off spring-boot-starter-swagger component dependencies. The code is as follows:
@ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inherited@Import ({SwaggerAutoConfiguration.class}) public @ interface EnableSwagger2Doc {}
The above code @ Import annotation introduces the Swagger2 autoconfiguration class SwaggerAutoConfiguration. When the annotation is configured above the application startup class, Swagger2 automatic configuration and its functions can be enabled.
Using spring-boot-starter-swagger component dependencies
The core code implementation of the spring-boot-starter-swagger component is briefly introduced above, and it is also easy to use. Add the corresponding dependent configuration to the Maven configuration of the chapter-2-spring-boot-config project. 1.5.0.RELEASE and above are supported. The configuration is as follows:
Com.spring4all spring-boot-starter-swagger 2.0
In addition, you need to configure the startup annotation class EnableSwagger2Doc above the ConfigApplication application launch class, as follows:
Import com.spring4all.swagger.EnableSwagger2Doc;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@EnableSwagger2Doc / / Open Swagger@SpringBootApplicationpublic class ConfigApplication {public static void main (String [] args) {SpringApplication.run (ConfigApplication.class, args);}}
Perform the ConfigApplication class startup, and after the console sees the output that runs successfully, open a browser to access the localhost:8080/swagger-ui.html address, and you can see the automatically generated Swagger API document, as shown in figure 2-7:
Figure 2-7 Swagger API document
API org.springframework.boot.autoconfigure.EnableAutoConfiguration annotation parameters
Exclude: Class array, excluding specific autoconfiguration classes.
ExcludeName: an array of strings that excludes autoconfiguration classes with specific names.
API org.springframework.boot.autoconfigure.ConditionalOnProperty annotation parameters
HavingValue: string, whether the expected value of the attribute matches.
MatchIfMissing: Boolean value, or match if the property value is not set.
Name: an array of strings, the name of the property to test.
Prefix: string, attribute prefix name.
Value: string with the same function as name.
API org.springframework.boot.autoconfigure.ConditionalOnClass annotation parameters
Name: an array of strings, the class name must exist.
Value: Class array, class must exist.
API org.springframework.boot.autoconfigure.ConditionalOnMissingBean annotation parameters
Annotation: annotate the Class array, matching the annotated decorated Bean.
Ignored: Class array, ignoring Bean of this type when matching.
IgnoredType: an array of strings, ignoring the Bean of the type name when matching.
Name: an array of strings that matches the Bean name to check.
Search: the SearchStrategy object that determines the contextual policy of the program through SearchStrategy.
Type: the string Shihu family that matches the name of the Bean type to be checked.
Value: Class array that matches the Bean type to check.
API org.springframework.boot.autoconfigure.ConditionalOnWebApplication annotation parameters
Type: ConditionalOnWebApplication.Type object that matches the corresponding Web application type.
This is the answer to the question about the principle of Spring Boot automatic configuration, core notes and how to use automatic configuration to achieve custom Starter components. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.