Spring boot web application practice

I have been using springboot for some time, and I always want to make a summary. Before the Department training, I just had to sort out a related document. Because of the outbreak, I stayed at home every day in order not to cause any disturbance to the country and society, and I sent out the articles sorted out before when I was free. The articles are not detailed enough. I refer to many articles, and the reference link is at the end of the article.

1 Introduction

SpringBoot is a new and open-source lightweight framework developed by the Pivotal team in 2013 and released in April 2014. It is designed based on Spring 4.0. It not only inherits the original excellent features of Spring framework, but also simplifies the whole process of building and developing Spring application by simplifying configuration. In addition, through integrating a large number of frameworks, Spring boot solves the problems of version conflicts of dependent packages and instability of references.

The features of SpringBoot are as follows:

(1) You can create independent Spring Applications, and based on their Maven or Gradle plug-ins, can create executable JARs and WARs;

(2) Embedded Servlet containers such as Tomcat or Jetty;

(3) Provides an automatically configured "starter" project object model (POMS) to simplify Maven To configure;

(4) Configure the Spring container as automatically as possible;

(5) Provide ready features such as metrics, health checks, and external configurations;

(6) There is absolutely no code generation and XML configuration is not required;

Differences between SpringBoot and SpringMvc:

Spring is an "engine";

Spring MVC is an MVC framework based on spring;

Spring Boot is a set of rapid development integration package based on spring conditional registration.

Some common notes of SpringBoot:

(1) The @ RestController and @ Controller specify a class as the annotation of the Controller and explain the differences

(2) @ RequestMapping method level mapping annotation, which is familiar to a small partner who has used Spring MVC

(3) The @ EnableAutoConfiguration and @ SpringBootApplication are class level annotations. The correct spring configuration is automatically guessed based on the jar that maven relies on. As long as the spring boot starter web dependency is introduced, the Spring MVC and tomcat containers are automatically configured by default

(4) The @ Configuration class level annotation is generally used to identify the class where the main method is located and complete the initialization of metadata bean s.

(5) The @ ComponentScan class level annotation automatically scans and loads all Spring components, including Bean injection, which is generally used on the class where the main method is located

(6) The @ ImportResource class level annotation, when we have to use an xml Configuration, @ ImportResource and @ Configuration are used to identify the class of this file resource.

(7) The @ Autowired annotation, usually combined with the @ ComponentScan annotation, automatically injects a Service or Dao level Bean

(8) The @ Component class level annotation is used to identify a Component. For example, if I set a filter by myself, Spring Boot will recognize it correctly only after this annotation is needed.

(9) Transaction annotation is OK. Method is method transaction and class is class transaction.

2 actual combat

2.1 project construction

Create maven project and introduce dependency


Create the application.properties file under resource

#Encoding settings
# tomcat config
# session timeout, in seconds

#Current application http port
#Access address

Create startup class

public class Application {
    private static Logger logger = LoggerFactory.getLogger(Application.class);
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        logger.info("Startup success");

Create Controller class

public class DemoController {
   @RequestMapping(value = "/hello", method = RequestMethod.GET)
   public String hello() {
      return "hello world";

Run the Application class, and then open the browser to access

2.2 configuration

2.2.1 local configuration

The Spring program will load the application.yml and application.properties configuration files from the following paths according to priority. At the same time, it will load the application.yml file first and then the application.properties configuration file.

(1) / config directory under the current directory

(2) Current directory

(3) / config directory in classpath

(4) classpath and directory

Therefore, it's easy to add configuration files outside. Create a new config folder in the directory where the jar is located, and then put the configuration files in it, or directly put the configuration files in the jar directory.

At the same time, different configurations can be read according to different environments of Profile, and a configuration file can be set for different environments, for example:

  • The configuration of dev environment is in application-dev.properties
  • The configuration of test environment is in application-test.properties

Specify which file to use in application.properties

spring.profiles.active = dev

2.2.2 user defined configuration file

2.2.3 remote configuration

At present, the popular remote configurations include spring official spring cloud config, apollo of Ctrip and ali nacos, which have their own advantages. Reference links 5, 6, 7

2.3 Swagger2 integration

Nowadays, front-end and back-end separation has gradually become a standard development method for Internet projects. The front-end and back-end are handed over to different personnel for development, but the communication cost in project development also increases. This part of communication cost mainly lies in the communication between front-end developers and back-end developers on the web Api interface. Swagger 2 can solve this problem very well. It can Generate Api interface documents dynamically, reduce communication cost and promote efficient development of the project.

pom.xml add dependency


Swagger configuration class

public class SwaggerConfigurer {
   public Docket createRestApi() {
      return new Docket(DocumentationType.SWAGGER_2)
   private ApiInfo apiInfo() {
      ApiInfoBuilder builder = new ApiInfoBuilder();
      builder.description("spring-boot-demo rest api File");
      return builder.build();

Use related notes in development

@Api(tags = {"DEMO Related interfaces"})
public class DemoController {
   @ApiOperation("HELLO Interface")
   @RequestMapping(value = "/hello", method = RequestMethod.GET)
   public String hello() {
      return "hello world";

Launch project, open browser to view interface information

2.4 Mybatis integration

<!--Paging plugins-->

application.properties add database related configuration

#Database related configuration
#maximum connection
#Maximum number of idle
#Minimum number of idle
#Number of initial connections
#Verify the idle connection in the pool, and recycle the connection if the verification fails
spring.datasource.tomcat.validation-query=SELECT 1
# mybatis

If you want to view sql logs, you need to configure the corresponding mapper log level to debug in logback

<logger name="com.spring.boot.demo.mapper" level="DEBUG" />

Open transaction

2.5 Security integration

SpringBoot is highly integrated with Security, and only primary usage is covered here.


Security configuration

2.6 component packaging

2.6.1 filter

Method 1:

Mode two:

2.6.2 interceptor

2.6.3 event listener

Method 1:

Mode two:

Create a new META-INF/spring.factories file under the resource path, and the configuration file will be automatically loaded by spring boot when it is loaded.

2.6.4 timer

Add @ EnableScheduling annotation in Application

Define task class

public class CustomTask {
    @Scheduled(cron = "0/15 * * * * ? ")
    public void taskDemo(){
        //Task begins

2.11 health examination

Spring boot's monitoring artifact, the activator, is very simple to integrate and easy to use, that is, to simply call and view the rest interface, which can be used in the monitoring environment with low requirements.

2.11.1 integration


Add a new configuration in the application.properties configuration file

#Monitoring related configuration
#Set the application root path for monitoring access. The default is / actor
#Expose monitoring provider, default is / health and / info
#Explicit shielding monitoring provider
#Open close application endpoint, not recommended
#Show health details

To start a project, it should be noted that since the general monitoring can be accessed without login, the corresponding url of monitoring should be filtered out in the security configuration.

Start the project and monitor the corresponding url through browser access

2.11.2 user defined application information

Add the following configuration in application.properties

#Basic information of application
info.app.name=spring boot demo

Access in browser

2.11.3 user defined detection endpoint

The actor comes with some detection endpoints, such as mysql, etc., but sometimes the project needs to customize some detection endpoints, but if you want to use the actor, you need to customize the detection endpoint.

public class CustomHealthIndicator extends AbstractHealthIndicator {

    protected void doHealthCheck(Health.Builder builder) throws Exception {
        builder.withDetail("message" ,"custom health indicator");

Access in browser

2.12 unit test

Spring boot's unit test is simple, just add the following dependencies to pom.xml


2.12.1 Service layer test

public class UserServiceTest {

    private UserDao userDao;

    public void getUser(){
        User user = userDao.getUserByUserName("admin");


2.12.2 Controller layer test

public class MenuControllerTest {
    private WebApplicationContext wac;
    private UserDao userDao;
    private MockMvc mvc;
    private MockHttpSession session;
    public void setupMockMvc(){
//Initialize MockMvc object
        mvc = MockMvcBuilders.webAppContextSetup(wac).build(); 
        session = new MockHttpSession();
        User user = userDao.getUserByUserName("admin");
        //The interceptor will determine whether the user is logged in, so a user is injected here

    public void getMenus() throws Exception{
        mvc.perform(MockMvcRequestBuilders.get(AipVersionConstant.API + AipVersionConstant.API_VERSION_01 + "/menu")

1.mockMvc.perform performs a request

2. Mockmvrequestbuilders. Get ("/ user/1") constructs a request, and the post request uses the. Post method

3. The content type (mediatype. Application? JSON? Utf8) represents that the data format sent by the sender is application/json;charset=UTF-8

4. Accept (mediatype. Application? JSON? Utf8) means that the data type the client wants to accept is application/json;charset=UTF-8

5. Inject a session (session) so that the interceptor can pass the

6.ResultActions.andExpect add assertions after execution

7. Resultactions. Andexpect (mockmvresultmatchers. Status(). Isok()) method to see if the status response code of the request is 200. If not, throw an exception. The test fails

8. Andexpect (mockmvresultmatchers. jsonPath ("$. Author"). value("Dudu MD independent blog")) here jsonPath is used to get whether the comparison of the author field is Dudu MD independent blog. If not, the test fails

9.ResultActions.andDo add a result processor to indicate what to do with the result. Use MockMvcResultHandlers.print() to output the whole response result information

2.13 static resources

The default static file path of SpringBoot is in the resource/static folder. If you want to change the static resource path, you can add or modify the following configuration in application.properties. Multiple paths are separated by commas.

#Static resource path
spring.resources.static-locations= classpath:./static

2.14 pack

Spring boot has built-in Tomcat or Jetty, so it is recommended to use jar package for packaging, but it also supports the way of War package for packaging, depending on the needs of each project.

2.14.1. Jar packaging

In general, jar packaging will cooperate with Maven assembly plugin for packaging.

        <!-- take jar Package and external configuration(zip,tar,tar.gz etc.) -->
                <!--jar Package name -->
                <!-- If it is war Package to annotate the contents of static resources -->

Create a new package.xml file in the following directory

<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <!-- Change to false Two layers of the same directory will not appear -->
        <!-- bin file -->
        <!-- configuration file -->
        <!-- Front end engineering documents -->

        <!-- Compiled the project itself jar Files, packing in zip Root directory of the file -->

2.14.2. War packaging

Removing tomcat dependency of spring boot in pom.xml

    <!-- If it's packed into war Or use jetty Should be removed SpringBoot Built in tomcat package -->

Add war package plug-in

        <!--If you want to web.xml Build with files WAR´╝îPlease set it to false. -->

Static file

In that project, add webapp directory to place static files, which will be automatically printed into war. It should be noted that creating web.xml under WEB-INF is an effective way to set filtering or sessionTime and other configurations in it.

3 reference link











Tags: Programming Spring Tomcat Maven xml

Posted on Tue, 04 Feb 2020 09:15:30 -0500 by Monk3h