Learning and understanding the springboot framework

Posted by meir4u on Sun, 31 Oct 2021 09:27:09 +0100

  • Handling exceptions through @ ControllerAdvice and @ ExceptionHandler annotations
    Note that the range of exceptions that @ ExceptionHandler can only handle is in this control class, which means that it is impossible to handle exceptions in other control classes. You can only add exception handling methods in each class, but one exception handling class can handle global exceptions,

  • Create a global exception handling class

1 Write error reporting control class
 //Test the error reporting method of the exception class
    @RequestMapping("showexcetpion")
    public String showexception(){
        int a = 10/0;
        return "Self study room at the end of summer";
    }
  ===================
  2 Create a global exception handling class
  package com.zixue.springbootmybatis.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/** Global exception handling class
*@ControllerAdvice Represents a global exception handling class
 * */
@ControllerAdvice
public class GlobalException {
    //The control class that handles nullpointer exceptions will handle global exceptions
    //This annotation is used to jump to the corresponding view according to the triggered exception,
    @ExceptionHandler(value = {java.lang.NullPointerException.class})
    public ModelAndView nullException(Exception e){
        //Create a page view
        ModelAndView mav = new ModelAndView();
        //View store exception information
        mav.addObject("err",e.toString());
        //Set exception handling page view name
        mav.setViewName("error");

        return mav;

    }
    @ExceptionHandler(value = {java.lang.ArithmeticException.class})
    public ModelAndView Mathexception(Exception e){
        //Create a page view
        ModelAndView mav = new ModelAndView();
        //View store exception information
        mav.addObject("err",e.toString());
        //Set exception handling page view name
        mav.setViewName("error");
        mav.addObject("exception","It's an arithmetic exception");

        return mav;

    }
}
============
page
 <span th:text="${exception}"></span>
  • Handle exceptions through the SimpleMappingExceptionResolver object
    Using @ ControllerAdvice and @ ExceptionHandler to handle global exceptions is very convenient, but note that each exception must write a method, which means that the exception global class will have many methods,
    You can use the SimpleMappingExceptionResolver object to define which page each exception jumps to, which is done in one method
1 Create a global exception handling class
package com.zixue.springbootmybatis.exception;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.Properties;

/** Global exception handling class 2
 *
 * */
@Configuration
public class GlobalException2 {

    //This method must return a SimpleMappingExceptionResolver object
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
        //This object is used to map exceptions to views
        //Create a properties object to store exceptions and pages
        Properties properties = new Properties();
        properties.put("java.lang.NullPointerException.class","error");
        properties.put("java.lang.ArithmeticException.class","errortwo");
        simpleMappingExceptionResolver.setExceptionMappings(properties);
        return simpleMappingExceptionResolver;
    }
}

=========
Exception page
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Error page</title>
</head>
<body>
        Null pointer exception
</body>
</html>
==========
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Error page</title>
</head>
<body>
    The arithmetic is abnormal
</body>
</html>

  • Custom global exception handling class
    With SimpleMappingExceptionResolver, why customize handlerExceptionResolver?
    Because SimpleMappingExceptionResolver cannot pass exception information, you need to customize an exception class to pass exception information. It's showing
1 Customize a global exception handling class
package com.zixue.springbootmybatis.exception;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** The custom handlerexceptionresolver object handles exceptions
 * The handlerExceptionResolver interface must be implemented
 *
 *
* */
@Configuration
public class GlobalException3 implements HandlerExceptionResolver {

    /** Parameter description parameter 1 and parameter 2 generate a request for an exception object
     * Parameter 3 is who the exception object is
     * Parameter 4 is the exception object
     * Now this method will enter this method regardless of any exception
     *  */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //Create a view object
        ModelAndView mav = new ModelAndView();
        //Judge different exception types and make different view jumps
        // instanceof is a java reserved keyword. It is used to test whether the object on the left is an instance of the class on the right, and the return is a boolean type
        if(ex instanceof NullPointerException){
            mav.setViewName("error");
        }if (ex instanceof ArithmeticException){
            mav.setViewName("errortwo");
        }
        //Store exception information in the view
        mav.addObject("errorinfo",ex.toString());
        return mav;
    }
}

===============
2 Create page ha
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Error page</title>
</head>
<body>
    The arithmetic is abnormal
    <span th:text="${errorinfo}"></span>
</body>
</html>
  • springboot integration test unit Junit
1 Add dependency
<!--Test module-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <!--exclude junit3 and junit4 Operation platform of-->
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
============
2 Test class
package com.zixue.springbootmybatis;
import com.zixue.springbootmybatis.Service.EmployeeService;
import com.zixue.springbootmybatis.pojo.Employee;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.sql.SQLException;
import java.util.List;
/** If there are multiple startup classes, you can specify which one to use for testing
 * */
@SpringBootTest(classes = SpringbootmybatisApplication.class)
class SpringbootmybatisApplicationTests {
    @Autowired
    private EmployeeService employeeService;

    @Test
    void contextLoads() throws SQLException {
        List<Employee> selectinfo = this.employeeService.selectinfo();
        selectinfo.stream().forEach(System.out::println);
    }

}

  • Spring boot for hot deployment
    1 hot deployment via DevTools
1 Add dependency
 <!--Hot deployment tool -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

2. Configure idea and set automatic compilation

ctrl + shift+alt+/

  • Spring bootadmin visual monitoring application
    1. To use springboot admin server, you need to establish a server and a client
    Server: it is the application of visual monitoring,
    Client: monitored items,
    Relationship: a server can monitor multiple clients,
    It is a third-party application,
    2. Build monitoring server application
    Note that spring boot admin starter server version 2.1.6 does not support spring boot 2.2. X at present. Only 2.1. x is supported
    All server-side projects should be built using spring boot version 2.1. X
1 Create project boot Add dependency 
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springbootservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootservice</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.1.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2 configuration file 
server.port=8089
3 Open the server application
package com.example.springbootservice;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAdminServer//Start the springboot admin server
public class SpringbootserviceApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootserviceApplication.class, args);
    }

}


Start successfully!!!

  • Spring boot packaging method
    1 add a packaging plug-in. boot comes with its own packaging plug-in
 <plugins>
            <!--Package plug-ins-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>

The function of this plug-in is to package the jar packages that the project depends on when packaging the project. If there is no dependent plug-in, there is no boot dependent package in the project after packaging,
2 manve package double click install

Topics: Java Spring Boot Back-end Framework