Write in frontπ« For more information, see SpringBoot 2 column
π This article summarizes the video of Raytheon in Silicon Valley
π Bloggers are still learning this knowledge
π If you find any problems, please point them out
ππZhawatai zaogao's blog home pageππ
1 configuration file
as mentioned before, configuration files can be roughly divided into two types: properties and yaml. Among them, properties is the most common type of configuration file: use the format of key value peer number to configure various parameters, and the suffix is Properties, which will not be repeated here. Let's talk about yaml file.
1.1 yaml file
The full name of yaml is YAML Ain't(isn't) Markup Language. It is an intuitive data serialization format that can be recognized by computers. yaml takes data as the core and is more concise than the traditional xml method. Reflected in the concise writing format and obvious expression level, it is very suitable for data centric configuration files. The suffix of yaml file is yml or yaml
1.1.1 basic grammar
- Use K: V for key value mapping. There should be a space before V as the separator
- Case sensitive
- Use indents to indicate hierarchical relationships
- You can't use the tab key to indent at the grammatical level. You should tap the space by hand. The number of spaces is not important. As long as it is the same number of spaces, it represents the same hierarchical relationship, so the indented spaces at the same level should be the same. However, the actual operation still uses the tab key, and there will be no problem
- Annotation uses # characters
1.1.2 data format
The following format constraints can be used for the data format of yaml file. This type of inline writing is noted with comments, and you can choose the customary form to use. Note that string type data can be enclosed without quotation marks, but if quotation marks are used, single quotation marks will output the escaped characters as strings, but double quotation marks will output the escaped characters after escaping. For example, \ n single quotation marks are \ n double quotation marks are escape characters.
1.2 keyword prompt during data binding
when configuring with yaml configuration file, there will be no prompt for code completion, which will not only greatly reduce the efficiency of code writing, but also increase the probability of error. Therefore, there is a method: add the configuration processor in the project to realize the keyword prompt when writing yaml files. The method is as follows:
Step 1: import related dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
Step 2: restart the project
click the run or restart button to restart the SpringBoot project
Step 3: Test
Step 4: in POM Add code to XML file
that is, do not enter the configuration processor into the jar package when typing the jar package, otherwise the efficiency of the project will be reduced
2 web development
2.1 storage and access of static resources
static resources can be understood as fixed pages at the front end, which contain HTML, CSS, JS, pictures, etc. they can be displayed directly without looking up the database or program processing.
Storage path:
When programming, all meta and inf resources are placed in any one of the following static folder names: meta, inf, and resources by default
Resource access method:
after starting the project, use the current project root path / + static resource name to access the static resources. All static resource mapping addresses are/**
when the static resource and controller request the same name, the resource parser will first look for the controller with that name to see if it can handle it. All requests that cannot be processed are handed over to the static resource processor to find the static resource. If the static resource cannot be found, the 404 page will be responded
Custom storage path and access method:
spring for configuration file web. resources. Modify the static locations configuration item to change the default static resource storage path.
Spring. For configuration file mvc. The static path pattern configuration item can be modified so that requests with a specified prefix can access static resources during access. As shown in the following figure, the corresponding static resources can only be accessed when using / res prefix + static resource name
2.2 webjars
webjars is to import the technical jars (such as jquery) required by the front end using dependencies. The official document of webjars is to show the dependencies corresponding to jars and directly copy them to POM XML file. Official documents of webjars: https://www.webjars.org/
2.3 web tips
2.3.1 index page
no matter the default or custom static resource path, just create an index HTML file, this page will be regarded as the welcome page of the project, that is, when accessing localhost: port number, you will access index HTML page. However, it should be noted that the access method of static resources cannot be customized, otherwise the above effect will be invalid.
2.3.2 small icons on Web pages
whether it is the default or custom static resource path, just add one named favicon ICO, which can be set as a small icon of the web page. At the same time, it should be noted that the access method of static resources cannot be customized, otherwise the above effect will be invalid.
2.4 analysis of Web scene source code
Effective automatic configuration class:
when SpringBoot starts, the default loading of xxxAutoConfiguration class (automatic configuration class) is that the relevant scenario takes effect, and the automatic configuration class of spring MVC function is webmvcoautoconfiguration
Configure binding:
The @ EnableConfigurationProperties annotation binds the relevant properties of the configuration file to the xxx configuration class and can be used to change the default configuration information. By analyzing the source code, we can see that there are the following annotations on the static class of webmvcoautoconfigurationadapter in the webmvcoautoconfiguration automatic configuration class, and there are two configuration classes in the annotation parameters. The binding relationship between the configuration class and the properties in the configuration file is as follows: webmvcproperties class --> spring. mvc WebProperties. class --> spring. web
@EnableConfigurationProperties({WebMvcProperties.class, WebProperties.class})
Analysis of resource processor in source code:
there is a rule in the source code of SpringBoot: the values of all parameters of the parameterized constructor will be taken from the container, so in the parameterized constructor in the static class of webmvccautoconfigurationadapter, all parameters will be obtained directly from the container.
//Resourceproperties resourceproperties -- > get and spring Resources bind to all the value objects //Webmvcproperties mvcproperties -- > get and spring MVC binds all the value objects //Listablebeanfactory beanFactory -- > beanFactory of spring //HttpMessageConverters -- > find all HttpMessageConverters //Resourcehandlerregistrationcustomizer -- > find the customization of the resource processor (focus on parsing) //Dispatcherservletpath -- > find the path of the resource //Servlet registrationbean -- > register servlets and filters for applications public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider, ObjectProvider<DispatcherServletPath> dispatcherServletPath, ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) { this.resourceProperties = resourceProperties; this.mvcProperties = mvcProperties; this.beanFactory = beanFactory; this.messageConvertersProvider = messageConvertersProvider; this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable(); this.dispatcherServletPath = dispatcherServletPath; this.servletRegistrations = servletRegistrations; }
by analyzing the addResourceHandlers method in the static class of webmvcaiutoconfigurationadapter, we can know the default rules of resource processing in the resource parser
public void addResourceHandlers(ResourceHandlerRegistry registry) { // Judge resource The value of add mappings is true / false (the default is true, and the configuration item can be modified in the configuration file) if (!this.resourceProperties.isAddMappings()) { // resource. If the value of add mappings is false, the access rules of all static resources are disabled, and the following sentence is output from the debug log logger.debug("Default resource handling disabled"); return; } // resource. If the value of add mappings is true, define the rule // Define the relevant configuration of the cache Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); // Define the resource storage rules and cache time of webjars if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } // Define access rules for static resources // this. mvcProperties. Getstaticpathpattern() -- > gets the access method of static resources. The default is\/** String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) // In the getStaticLocations() method .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } }
Analysis of welcome page in source code:
@Bean public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) { // The parametric function of welcomePageHandlerMapping is shown in the following picture WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider)); welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations()); return welcomePageHandlerMapping; }
the following figure explains why: customizing the access method of static resources will make the welcome page ineffective. This part of the condition has been written dead in the source code of SpringBoot.