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

What's the use of Spring Boot?

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

Share

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

This article mainly introduces the use of Spring Boot, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

1. Getting started with Spring Boot

Spring Boot is a relatively new project in the Spring community. The purpose of the project is to help developers create Spring-based applications and services more easily, let more people get started with Spring faster, and make Java development as productive as Ruby on Rails. Provides a fixed, convention-over-configuration style framework for the Spring ecosystem.

Spring Boot has the following characteristics:

Provide a faster getting started experience for Spring-based development

Right out of the box, no code generation, no XML configuration. You can also modify the default values to meet specific needs.

Provides some common non-functional features in large projects, such as embedded server, security, indicators, health detection, external configuration and so on.

Spring Boot is not a functional enhancement to Spring, but rather provides a quick way to use Spring.

1.1 simple example

Start by creating a generic Maven project with a pom.xml and a basic src/main/java structure.

1.1.1 pom.xml Fil

4.0.0com.nes.spring.bootSpringBootDemo10.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 1.3.0.RELEASE org.springframework.boot spring-boot-starter-web org.apache.maven.plugins maven-compiler-plugin 2.5.1 1.7 1.7 org.springframework.boot spring-boot-maven-plugin org.springframework springloaded 1.2.5.RELEASE

1.1.2 description of pom

First of all, the addition of the parent pom is relatively simple, and spring-boot-starter-parent contains a large number of configured dependency management, so you don't need to write a version number when adding these dependencies to your project.

It is easy to use a parent pom, but in some cases we already have a parent pom. If you cannot add it directly, you can use the following ways:

Org.springframework.boot spring-boot-dependencies 1.2.3.RELEASE pom import

1.1.3 about the java.version attribute

Although the above pom.xml does not appear this attribute, here is a special reminder.

Spring uses jdk1.6 by default. If you want to use jdk1.8, you need to add java.version to the attributes of pom.xml, as follows:

1.8

1.1.4 add spring-boot-starter-web dependency

Spring can support a specific function by adding dependencies such as spring-boot-starter-*.

The ultimate goal of our example is to implement the web function, so this dependency is added.

1.1.5 add the spring-boot-maven-plugin plug-in

The plug-in supports a variety of functions, two of which are commonly used. The first is to package the project as an executable jar package.

Executing mvn package under the project root will generate an executable jar package, which contains all dependent jar packages. Only this jar package is needed to run the program, which is very convenient to use. After the command is executed, it also retains a jar package for XXX.jar.original, which contains separate parts of the project.

After generating this executable jar package, execute java-jar xxxx.jar on the command line to start the project.

Another command is mvn spring-boot:run, which starts the project directly using tomcat (the default).

In our development process, we need to modify frequently, in order to avoid repeatedly starting the project, we can enable hot deployment.

1.1.6 Hot deployment of spring-loaded

The Spring-Loaded project provides a powerful hot deployment function, which can be hot deployed when adding / deleting / modifying methods / fields / interfaces / enumerations and other code, which is very fast and convenient.

To use this feature in Spring Boot is as simple as adding dependencies under the spring-boot-maven-plugin plug-in:

Org.springframework springloaded 1.2.5.RELEASE

Once added, hot deployment is supported through mvn spring-boot:run startup.

Note: when using hot deployment, you need IDE to compile the class to take effect, you can turn on the automatic compilation function, so that when you save the changes, the class will automatically reload.

1.2 create an application class

Let's create an Application class:

@ RestController@EnableAutoConfigurationpublic class Application {@ RequestMapping ("/") String home () {return "Hello World!";} @ RequestMapping ("/ now") String hehe () {return "now time:" + (new Date ()) .toLocaleString ();} public static void main (String [] args) {SpringApplication.run (Application.class, args);}}

1.2.1 Note

Spring Boot recommends that the main configuration class where our main method is located be configured under the root package name.

Com +-example +-myproject +-Application.java +-domain | +-Customer.java | +-CustomerRepository.java +-service | +-CustomerService.java +-web +-CustomerController.java

There is a main method in Application.java.

Because of the default package-related annotations, the default package name is the package in which the current class resides, such as @ ComponentScan, @ EntityScan, @ SpringBootApplication annotations. (all the packages in which Ann's current Application.java is located are scanned as Scan)

1.2.2 @ RestController

Because our example is to write a web application, writing this annotation is equivalent to adding both @ Controller and @ ResponseBody annotations.

1.2.3 @ EnableAutoConfiguration

Spring Boot recommends that there is only one class with this annotation.

@ EnableAutoConfiguration function: Spring Boot will automatically configure projects based on the dependencies of your jar package.

For example, when you have a HSQLDB dependency under your project, Spring Boot will create the default in-memory database data source DataSource, and if you create your own DataSource,Spring Boot, you will not create the default DataSource.

If you do not want Spring Boot to be created automatically, you can configure the exclude property of the annotation, for example:

@ Configuration@EnableAutoConfiguration (exclude= {DataSourceAutoConfiguration.class}) publicclassMyConfiguration {}

1.2.4 @ SpringBootApplication

Because a large number of projects are added to the main configuration classes

@ Configuration,@EnableAutoConfiguration,@ComponentScan three annotations.

So SpringBoot provides the @ SpringBootApplication annotation, which replaces the above three annotations (implemented using Spring annotation inheritance).

1.2.5 launch Project SpringApplication.run

The easiest way to start the Spring Boot project is to execute the following method:

SpringApplication.run (Application.class, args)

This method returns an ApplicationContext object of the specific type AnnotationConfigApplicationContext or AnnotationConfigEmbeddedWebApplicationContext when using annotations and the second when web is supported.

In addition to the above method, you can also use the following methods:

SpringApplication application = new SpringApplication (Application.class); application.run (args)

SpringApplication includes some other methods that can be configured, and if you want to do some configuration, you can use this way.

In addition to the direct approach above, you can also use SpringApplicationBuilder:

New SpringApplicationBuilder () .showBanner (false) .sources (Application.class) .run (args)

When using SpringMVC, because you need to use a child container, you need to use SpringApplicationBuilder, which has a child (xxx...) Method can add child containers.

1.3 Operation

Execute the main method directly in IDE, and then access http://localhost:8080.

Alternatively, you can use the mvn mentioned above, which can be packaged as an executable jar package, and then execute java-jar xxx.jar.

Or execute mvn spring-boot:run to run the project.

2. Configuration and use of Spring Boot properties

Spring Boot allows you to use the code of the same application in different environments through external configuration, simply by injecting properties or modifying the default configuration through the configuration file.

2.1 Spring Boot supports multiple external configurations

The priorities of these methods are as follows:

Command line argument

JNDI property from java:comp/env

Java system Properties (System.getProperties ())

Operating system environment variable

The random.* attribute value of the RandomValuePropertySource configuration

Application- {profile} .properties or application.yml (with spring.profile) configuration files outside the jar package

Application- {profile} .properties or application.yml (with spring.profile) configuration files inside the jar package

Application.properties or application.yml (without spring.profile) configuration files outside the jar package

Application.properties or application.yml (without spring.profile) configuration files inside the jar package

@ PropertySource on @ Configuration annotation class

Default properties specified by SpringApplication.setDefaultProperties

2.1.1 Command line arguments

Parameters are passed in the java-jar app.jar-name= "Spring"-server.port=9090 mode.

Parameters are passed in the form of-xxx=xxx.

The parameters that can be used can be defined by ourselves or the default parameters in Spring Boot.

Many people may be concerned about issues such as how to configure web ports. These are the parameters provided in Spring Boot. Some of the available parameters are as follows:

# LOGGINGlogging.path=/var/logslogging.file=myapp.loglogging.config= # location of config file (default classpath:logback.xml for logback) logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF) # EMBEDDED SERVER CONFIGURATION (ServerProperties) server.port=8080server.address= # bind to a specific NICserver.session-timeout= # session timeout in secondsserver.context-parameters.*= # Servlet context init parameters, e.g. Server.context-parameters.a=alphaserver.context-path= # the context path Defaults to'/ 'server.servlet-path= # the servlet path, defaults to' /'

Note: the command line arguments come after app.jar!

Command line configuration can be disabled through SpringApplication.setAddCommandLineProperties (false).

2.1.2 Java system Properties

Note that the Java system attribute location java-Dname= "isea533"-jar app.jar, the properties that can be configured are all the same, with different priorities.

For example, java-Dname= "isea533"-jar app.jar-name= "Spring!" The name value in the is Spring!

2.1.3 operating system environment variables

Anyone who has configured JAVA_HOME should know this one.

It is important to note that some OS can not be used. This name, such as server.port, can be configured using SERVER_PORT.

2.1.4 RandomValuePropertySource

Where random numbers are used in the system, for example:

My.secret=random.valuemy.number= {random.int} my.bignumber=random.longmy.number.less.than.ten= {random.int (10)} my.number.in.range=$ {random.int [1024pr 65536]}

Random.int* supports the value parameter and the max parameter, and when the max parameter is provided, value is the minimum value.

2.1.5 Application profile (.properties or .yml)

Write directly in the configuration file:

Name=Isea533server.port=8080

Configuration files in .yml format such as:

Name: Isea533 server: port: 8080

It is easier to use a configuration file in .yml format when there is a prefix. For more information about the use of the .yml configuration file, please see here.

Note: when using .yml, there must be a space between the value of the attribute name and the colon. If name:Isea533 is correct, name:Isea533 is wrong.

2.1.5.1 location of the property profile

Spring looks for application.properties or application.yml from the / config directory under classpath or from the root directory of classpath.

/ config takes precedence over classpath root directory

2.1.6 @ PropertySource

This annotation can specify a specific property profile with a low priority.

2.1.7 SpringApplication.setDefaultProperties

For example:

SpringApplication application = new SpringApplication (Application.class); MapdefaultMap = new HashMap (); defaultMap.put ("name", "Isea-Blog"); / / it can also be a Properties object application.setDefaultProperties (defaultMap); application.run (args); 2.2 apply (use) attribute 2.2.1 @ Value ("${xxx}"), which is the easiest way to inject property values through the @ Value annotation. 2.2.2 @ ConfigurationPropertiesSpring Boot can easily inject attributes into a configuration object. For example: my.name=Isea533my.port=8080my.servers [0] = dev.bar.commy.servers [1] = foo.bar.com corresponding object: @ ConfigurationProperties (prefix= "my") publicclassConfig {private String name;private Integer port;private List servers = newArrayList (); public String geName () {returnthis.name;} public Integer gePort () {returnthis.port;} public ListgetServers () {returnthis.servers;}}

Spring Boot automatically injects attributes with the prefix prefix= "my" as my.

Spring Boot automatically converts types, so you need to pay attention to initializing List in the configuration when using List!

Spring Boot also supports nested attribute injection, such as:

Name=isea533jdbc.username=rootjdbc.password=root...

Corresponding configuration class:

@ ConfigurationPropertiespublicclassConfig {private String name;privateJdbcjdbc; class Jdbc {private String username;private String password;//getter... } public Integer gePort () {returnthis.port;} publicJdbcgetJdbc () {returnthis.jdbc;}}

Attributes that begin with jdbc are injected into the Jdbc object.

2.2.3 use @ ConfigurationProperties on the @ Bean method

For example:

ConfigurationProperties (prefix = "foo") @ BeanpublicFooComponentfooComponent () {...}

Spring Boot injects the attributes that begin with foo into the FooComponent object by name matching.

2.2.4 attribute placeholder

For example:

App.name=MyAppapp.description=$ {app.name} is a Spring Boot application

The previously configured properties can be referenced in the configuration file (all previously configured priorities can be used here).

You can also set the default value through a method such as ${app.name: default name}, which is used when the referenced property is not found.

Because the ${} mode is handled by Maven. If you inherit spring-boot-starter-parent from pom

Spring Boot has changed the default ${} mode of maven-resources-plugins to @ @ mode, such as @ name@.

If you introduced Spring Boot, you can modify it to use other delimiters

2.2.5 you can also shorten command parameters through attribute placeholders

For example, to modify the default port of web, you need to use the-server.port=9090 method. If you write it in the configuration:

Server.port=$ {port:8080}

Then you can use the shorter-port=9090, and use the default value of 8080 when this parameter is not provided.

2.2.6 matching rules for attribute names

For example, there are the following configuration objects:

@ Component@ConfigurationProperties (prefix= "person") publicclassConnectionSettings {private String firstName;}

The property names that can be used by firstName are as follows:

Person.firstName, the standard hump naming

Person.first-name, dotted line (-) split method, recommended in .properties and .yml configuration files

PERSON_FIRST_NAME, in the form of uppercase underscores, is recommended in system environment variables

2.2.7 attribute validation

You can use JSR-303 annotations for verification, for example:

Component@ConfigurationProperties (prefix= "connection") publicclassConnectionSettings {@ NotNullprivateInetAddressremoteAddress;//... Getters and setters}

2.3 Last

The above is the content of the configuration and use of the Spring Boot property. If there are some inadequacies or readers have more questions, you can check out the complete Spring Boot documentation or Externalized Configuration.

3. Spring Boot integrates MyBatis

3.1. Spring Boot integrated druid

Druid has many configuration options, and druid can be easily configured using Spring Boot's configuration file.

Write in the application.yml configuration file:

Spring:datasource: name: test url: jdbc:mysql://192.168.16.137:3306/test username: root password:# uses druid data source type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select'x 'testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20

Here you can configure it through type: com.alibaba.druid.pool.DruidDataSource!

3.2. Spring Boot integrated MyBatis

There are two ways for Spring Boot to integrate MyBatis. One simple way is to use the official MyBatis:

Mybatis-spring-boot-starter

Another way is to still use a configuration similar to mybatis-spring, which requires you to write some code, but you can easily control the configuration of MyBatis.

3.2.1. Mybatis-spring-boot-starter mode

Add dependencies in pom.xml:

Org.mybatis.spring.bootmybatis-spring-boot-starter1.0.0

The mybatis-spring-boot-starter dependency tree is as follows:

Version 3.3.0 used by mybatis can be obtained by:

Mybatis: mapperLocations: classpath:mapper/*.xmltypeAliasesPackage: tk.mapper.model

In addition to the two common configurations above, there are:

The path to the mybatis.config:mybatis-config.xml profile

Mybatis.typeHandlersPackage: scan typeHandlers's package

Mybatis.checkConfigLocation: check if the configuration file exists

Mybatis.executorType: sets the execution mode (SIMPLE, REUSE, BATCH). Default is SIMPLE.

3.2.2 mybatis-spring mode

This method is close to the usual usage. You need to add mybatis and mybatis-spring dependencies.

Then create a MyBatisConfig configuration class:

/ * MyBatis basic configuration * * @ authorliuzh * @ since 2015-12-19 10:11 * / @ Configuration@EnableTransactionManagementpublicclassMyBatisConfigimplementsTransactionManagementConfigurer {@ AutowiredDataSourcedataSource;@Bean (name = "sqlSessionFactory") publicSqlSessionFactorysqlSessionFactoryBean () {SqlSessionFactoryBean bean = newSqlSessionFactoryBean (); bean.setDataSource (dataSource); bean.setTypeAliasesPackage ("tk.mybatis.springboot.model"); / / paging plug-in PageHelperpageHelper = newPageHelper (); Properties properties = new Properties (); properties.setProperty ("reasonable", "true"); properties.setProperty ("supportMethodsArguments", "true") Properties.setProperty ("returnPageInfo", "check"); properties.setProperty ("params", "count=countSql"); pageHelper.setProperties (properties); / / add plug-in bean.setPlugins (new Interceptor [] {pageHelper}); / / add XML directory ResourcePatternResolver resolver = newPathMatchingResourcePatternResolver (); try {bean.setMapperLocations (resolver.getResources ("classpath:mapper/*.xml")); returnbean.getObject ();} catch (Exception e) {e.printStackTrace (); thrownewRuntimeException (e) } @ BeanpublicSqlSessionTemplatesqlSessionTemplate (SqlSessionFactorysqlSessionFactory) {returnnewSqlSessionTemplate (sqlSessionFactory);} @ Bean@OverridepublicPlatformTransactionManagerannotationDrivenTransactionManager () {returnnewDataSourceTransactionManager (dataSource);}}

The above code creates a SqlSessionFactory and a SqlSessionTemplate, adds the @ EnableTransactionManagement annotation to support annotated transactions, and returns a PlatformTransactionManagerBean.

Also note that there is no MapperScannerConfigurer in this configuration. If we want to scan the Mapper interface of MyBatis, we need to configure this class, which we need to put into a separate class.

/ * MyBatis scanning interface * * @ authorliuzh * @ since 2015-12-19 14:46 * / @ Configuration// Note: due to the early execution of MapperScannerConfigurer, the following note @ AutoConfigureAfter (MyBatisConfig.class) publicclassMyBatisMapperScannerConfig {@ BeanpublicMapperScannerConfigurermapperScannerConfigurer () {MapperScannerConfigurermapperScannerConfigurer = newMapperScannerConfigurer (); mapperScannerConfigurer.setSqlSessionFactoryBeanName ("sqlSessionFactory"); mapperScannerConfigurer.setBasePackage ("tk.mybatis.springboot.mapper"); / / configure generic mappersPropertiesproperties=newProperties () Properties.setProperty ("mappers", "tk.mybatis.springboot.util.MyMapper"); properties.setProperty ("notEmpty", "false"); properties.setProperty ("IDENTITY", "MYSQL"); / / the MapperScannerConfigurer of the generic Mapper used here, all with the following method mapperScannerConfigurer.setProperties (properties); returnmapperScannerConfigurer;}}

This configuration must pay attention to @ AutoConfigureAfter (MyBatisConfig.class), you must have this configuration, otherwise there will be an exception. The reason is that this class executes relatively early, because sqlSessionFactory does not yet exist, subsequent execution error. After completing the above configuration, you can use MyBatis.

3.3. About paging plug-ins and generic Mapper integration

An example of a paging plug-in as a plug-in is found in the above code.

Generic Mapper configuration is actually used when configuring MapperScannerConfigurer

Tk.mybatis.spring.mapper.MapperScannerConfigurer is fine, and the configuration properties use Properties.

3.4. Spring Boot integrates the basic project of MyBatis

Project address: https://github.com/wudongqiang/MyBatis-Spring-Boot

Information about the paging plug-in and generic Mapper can be found at the address above.

4. Spring Boot static resource processing

The default handling of Spring Boot is sufficient, and by default Spring Boot uses the various properties configured in WebMvcAutoConfiguration.

It is recommended to use the default processing method of Spring Boot, and the places that need to be configured can be modified through the configuration file.

But if you want to have full control of Spring MVC, you can add @ EnableWebMvc to the configuration class of the @ Configuration annotation. After adding this annotation, the configuration in WebMvcAutoConfiguration will not take effect, and you need to configure everything you need. The configuration method in this case is recommended to refer to the WebMvcAutoConfiguration class.

The following content of this article aims at the default handling of Spring Boot, and part of the configuration is set in the application.yml configuration file.

The default path for 1.spring boot to load files is

/ META-INF/resources/ / resources/ / static/ / public/private static final String [] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"}

All local static resources are configured under classpath, not under webapp

4.1. Configure Resource Mappin

Spring Boot default configuration / maps to / static (or / public, / resources,/META-INF/resources), / webjars/ maps to

Classpath:/META-INF/resources/webjars/ .

Note: the / static and other directories above are all under classpath:.

If you want to add mapping such as / mystatic/** to classpath:/mystatic/, you can have your configuration class inherit WebMvcConfigurerAdapter, and then override the following method:

@ OverridepublicvoidaddResourceHandlers (ResourceHandlerRegistry registry) {registry.addResourceHandler ("/ mystatic/**") .addResourceLocations ("classpath:/mystatic/");}

This method will add / mystatic/** mapping to classpath:/mystatic/, on the default basis without affecting the default mode and can be used at the same time.

Static resource mapping also has a configuration option, which is written in .properties here for simplicity:

Spring.mvc.static-path-pattern=/** # Path pattern used forstatic resources.

This configuration affects the default /, for example, when changed to / static/, only requests such as / static/js/sample.js can be mapped (/ js/sample.js before modification). This configuration can only write one value, unlike most configurations that can be separated by commas.

4.2. Attention to use

For example, there is a directory structure as follows:

└─ resources │ application.yml │ ├─ static │ ├─ css │ │ index.css │ ││ └─ js │ index.js │ └─ templatesindex.ftl

How do you reference the above static resources in index.ftl?

Write as follows:

Note: the default configuration of / * * maps to / static (or / public, / resources,/META-INF/resources)

When you request / css/index.css, the Spring MVC will be found under the / static/ directory.

If / static/css/index.css is configured, there is no / static directory under all the directories configured above, so the resource file will not be found!

So when writing static resource locations, don't bring the mapped directory name (such as / static/,/public/,/resources/,/META-INF/resources/)!

4.3. Use WebJars

WebJars: http://www.webjars.org/

For example, using jquery, add dependencies:

Org.webjarsjquery1.11.3

You can then use it as follows:

You may have noticed the version 1.11.3 in href. If we only use it this way, then we have to manually modify href when we switch the version number. It's troublesome, and we can solve it in the following way.

First add dependencies to pom.xml:

Org.webjarswebjars-locator

Add a WebJarController:

@ ControllerpublicclassWebJarController {privatefinalWebJarAssetLocatorassetLocator = newWebJarAssetLocator (); @ ResponseBody@RequestMapping ("/ webjarslocator/ {webjar} / * *") publicResponseEntitylocateWebjarAsset (@ PathVariable String webjar, HttpServletRequest request) {try {String mvcPrefix = "/ webjarslocator/" + webjar + "/"; String mvcPath = (String) request.getAttribute (HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String fullPath = assetLocator.getFullPath (webjar, mvcPath.substring (mvcPrefix.length ()); returnnewResponseEntity (newClassPathResource (fullPath), HttpStatus.OK);} catch (Exception e) {returnnewResponseEntity (HttpStatus.NOT_FOUND) }}}

Then use it as follows:

Note: there is no need to write the version number here, but pay attention to write url, just remove the version number on the basis of the original url, other can not be less!

4.4. Static resource version management

Spring MVC provides the ability to map static resource versions.

Purpose: when the content of our resources changes, the user's local static resources are still old resources due to browser cache. in order to prevent problems caused by this situation, we may manually add a version number or other means when requesting url.

Version numbers are as follows:

The features provided by Spring MVC can easily help us solve similar problems.

There are two solutions to Spring MVC.

Note: the following configuration method is for freemarker template, and other configuration methods can be referenced.

4.4.1. Resource name-md5 mode

The copy code is as follows:

Spring automatically reads the resource md5 and adds it to the name of the index.css, so when the content of the resource changes, the file name changes and the local resource is updated.

Configuration method:

Do the following configuration in application.properties:

Spring.resources.chain.strategy.content.enabled=truespring.resources.chain.strategy.content.paths=/**

After this configuration, all static resources requested by / * will be processed as shown in the above example.

It's not over yet. We have to do something special when we write the resource url.

First of all, add the following configuration:

@ ControllerAdvicepublicclassControllerConfig {@ AutowiredResourceUrlProviderresourceUrlProvider;@ModelAttribute ("urls") publicResourceUrlProviderurls () {returnthis.resourceUrlProvider;}}

Then write the page in the following way:

The copy code is as follows:

Use urls.getForLookupPath ('/ css/index.css') to get the processed resource name.

4.4.2. Version number mode

Do the following configuration in application.properties:

Spring.resources.chain.strategy.fixed.enabled=truespring.resources.chain.strategy.fixed.paths=/js/**,/v1.0.0/**spring.resources.chain.strategy.fixed.version=v1.0.0

You need to pay special attention to the configuration here, configuring the value of version in paths.

When writing the page, it is written as follows:

Note that the urls.getForLookupPath,urls configuration method is still used here, as shown in the previous method.

On the actual page of the request, it will appear as follows:

You can see that the address here is / v1.0.0/js/index.js.

4.5. Static resource version management process

The urls.getForLookupPath method is first called in the Freemarker template, returning a / v1.0.0/js/index.js or / css/index-2b371326aa93ce4b611853a309b69b29.css.

At this point, the content on the page is the address of the processed resource. After that, the browser initiates a request.

Let's talk separately here.

The first way of md5

Request / css/index-2b371326aa93ce4b611853a309b69b29.css, our md5 configured paths=/**, so Spring MVC will try to see if the url contains -. If it does, it will remove the latter part, and then go to the mapped directory (such as / static/) to find the / css/index.css file and return it if it can be found.

The second version

Request / v1.0.0/js/index.js.

If / v1.0.0 is not configured in our paths, the above request address will not be processed as a version, so the above resources will not be found.

If / v1.0.0 is configured, Spring will remove / v1.0.0 and look for / js/index.js, which will eventually be found under / static/.

Thank you for reading this article carefully. I hope the article "what's the use of Spring Boot" shared by the editor will be helpful to everyone? at the same time, I also hope that you will support and pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

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