Spring Boot framework usage guide

overview

Spring official website: https://spring.io/projects

Spring Boot is a brand new framework created on the basis of the Spring framework. It is a sub-project in the Spring project and belongs to Spring products like Spring-framework.

Spring Boot is called scaffolding for building programs. Its main function is to quickly build a huge Spring project, and reduce all xml configurations as much as possible, so that it can be used out of the box and get started quickly, allowing developers to focus on business rather than configuration.

Spring Boot simplifies the development of Spring-based applications and provides out-of-the-box settings for the Spring platform and third-party libraries (provides default settings, and the package that stores the default configuration is the starter). Most Spring Boot applications only need a small amount of Spring configuration. Spring Boot has built-in tomcat, so there is no need to configure tomcat separately.

The purpose of Spring Boot design is to simplify the construction and development process of Spring applications. It not only has all the excellent features of Spring, but also has the following notable features:

  • Provide easier use and rapid development skills for Spring development
  • With out-of-the-box default configuration function, it can be automatically configured according to project dependencies
  • It has a more powerful service system, including embedded services, security, performance indicators, health checks, etc.
  • Absolutely no code generation, XML configuration is no longer required, making the application more lightweight and flexible
  • Spring Boot provides perfect integration for the use of some third-party technologies and is easy to use.

SpringBoot project construction

Basic dependency introduction

Spring Boot official website version list: https://spring.io/projects/spring-boot#learn

  • RELEASE GA: General Availability, the officially released version, officially recommended to use this version.
  • SNAPSHOT: Snapshot version, which can be used stably and is still being improved.
  • PRE: preview version, internal beta version, mainly for developers and testers to test and find bugs, it is not recommended to use.
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>spring-boot-ssm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- 使用SpringBoot框架必须引入 spring-boot-starter-parent 作为父项目 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
    </parent>
    
    <properties>
        <!-- 设置JDK版本 -->
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
        <!-- web启动器 -->
        <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>
        
        <!---- 数据库相关 ---->
        <!-- jdbc启动器,spring-boot-starter-jdbc默认集成了HikariCP连接池 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- druid连接池启动器 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 持久层框架启动器 -->

        
        <!---- 工具类 ---->
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

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

startup class

App.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Spring Boot configuration

Annotations for Spring loaded configuration

  • @Configuration : Declare a class as a configuration class instead of an xml file

  • **@Bean **: Declare on the method, add the return value of the method to the Bean container instead of <bean>the label

  • @Value : attribute injection, instead of attribute injection in xml

    Format: @Value("${property}")

  • @PropertySource : Load the specified property file (*.properties) into Spring's Environment

    Can be used with @Value and @ConfigurationProperties

    • Combination of @PropertySource and @Value:

      You can inject the property variable value in the custom property file into the member variable annotated with @Value of the current class.

    • Combination of @PropertySource and @ConfigurationProperties:

      The properties file can be bound to a Java class, and the variable values ​​in the properties file can be injected into the member variables of the Java class.

@ConfigurationProperties: auto-configuration bindings

@ConfigurationProperties : used to automatically configure the properties of the binding yml configuration file and the properties of the java object

Support attributes:

  • value / prefix attribute: configuration file configuration item prefix
  • ignoreInvalidFields attribute: the default is false, if the value type does not match, an exception will be thrown
  • ignoreUnknownFields attribute: The default is true, ignoring unknown fields in the object

Usage 1 : mark on the class, convert configuration file configuration items to bean objects

  • Notice:
    • Classes annotated with @ConfigurationProperties need to be registered in the spring container in two ways:
      • Method 1: Use @componet and other IOC annotations on classes marked with @ConfigurationProperties annotations
      • Method 2: Mark @EnableConfigurationProperties(bean class name.class) on the class marked with IOC annotations such as @componet or on the configuration class
    • Requires no-argument constructor, getter and setter methods
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "app.mycar")
public class Car {
    
    
    private int price;
    private String brand;
}
@Configuration
@EnableConfigurationProperties(Car.class) 
public class Config {
    
    
}

Usage 2 : Mark on the method of the configuration class, use it with @bean, and bind third-party properties

@Configuration
public class DbConfig {
    
    
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource datasource(){
    
    
        return new DruidDataSource();
    }
}

Environment: Get running environment variables

The Environment in Spring is used to represent the runtime environment of the entire application. You can use the Environment class to obtain configuration information in the entire runtime environment.

method:

public String getProperty(String key)
public <T> T getProperty(String key, Class<T> targetType)
    
// 注:key为配置文件中的key

Example:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration  // 声明这个类是一个配置类
@PropertySource(value = "classpath:user.properties") //加载配置文件
public class UserConfig {
    
    
    @Autowired
    private Environment environment;
    
    @Bean   //创建User对象,交给spring容器 User对象中的值从配置文件中获取
    public User getUser() {
    
    
        User user = new User();
        user.setUsername(environment.getProperty("user.username"));
        user.setPassword(environment.getProperty("user.password"));
        return user;
    }
}

Supported profile types and priorities

  • application.properties
  • application.yml
  • application.yaml

The priority of configuration files being loaded is:

  • properties > yml > yaml

  • If the same configuration is configured in multiple configuration file types, the configuration with higher priority will take effect

Default configuration and common basic configuration

Spring Boot encapsulates a large number of default configurations:

  • Document directory of each version of Spring boot: https://docs.spring.io/spring-boot/docs/

  • The default configuration list of SpringBoot 2.3.0.RELEASE version (other versions are similar):

    https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/appendix-application-properties.html

Common basic configuration of Spring Boot:

server:
  # 服务端口号,默认8080
  port: 8080

logging:
  level:
    # 微服务的日志配置。格式:包路径: 日志级别
    com.test: debug

spring:
  application:
    name: test-service
  datasource:     # 数据源配置
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/leyou?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

Spring MVC configuration

port configuration

Set web access port

server:
 port: 8080

log configuration

The log levels are divided into FATAL, ERROR, WARN, INFO, DEBUG, ALL or user-defined levels.

Log4j recommends using only four levels, the priority from high to low is ERROR, WARN, INFO, DEBUG

  • In the production environment of an enterprise, it is generally set to the INFO level, which means that the logs of the INFO level and above are printed, and the logs of the DEBUG level and below are not printed

  • Development and testing environment, generally set to DEBUG level, which means that all levels of logs can be output

Log level control:

logging:
  level:
    com.test: debug
    org.springframework.web: debug

illustrate:

  • logging.level: Fixed writing method, indicating that the following is the log level configuration, and other log related configurations can also be used
  • com.test and org.springframework are the specified package names, and the subsequent configuration is only valid for this package

static resources

The default static resource path is:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public

As long as static resources are placed in any of these directories, SpringMVC will handle them.

Generally, static resources are placed classpath:/static/in the directory.

interceptor

  • If you want to keep some of the default MVC features of Spring Boot, but also want to customize some MVC configurations (including: interceptors, formatters, view controllers, message converters, etc.), you can make a class implement the interface and add annotations, but you WebMvcConfigurercannot @Configurationadd @EnableWebMvcannotations

  • If you want to customize HandlerMapping, HandlerAdapter, ExceptionResolverand other components, you can create an WebMvcRegistrationsAdapter instance to provide the above components

  • If you want to fully customize Spring MVC without retaining all the features provided by Spring Boot, you can define your own classes and add @Configurationannotations and @EnableWebMvcannotations

  1. Custom interceptor (implements the HandlerInterceptor interface)
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        log.debug("preHandle方法执行...");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    
        log.debug("postHandle方法执行...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    
        log.debug("afterCompletion方法执行...");
    }
}
  1. Add configuration class (implement WebMvcConfigurer interface), register interceptor
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    
    
    /**
     * 注册自定义拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        // 通过registry来注册拦截器,通过addPathPatterns来添加拦截路径
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/login");  // 这个地址的不拦截
    }
}

ApplicationRunner interface

  • method:

    Only one run(ApplicationArguments args) method is defined

    The parameter ApplicationArguments of the run method can obtain the command parameters of the current project execution (for example, when the project is executed as a jar, the parameters can be obtained through ApplicationArguments).

    Since this method is executed after the container is started, other injected beans can also be obtained from the spring container.

  • scenes to be used:

    When the springBoot project starts, if you want to execute a certain piece of code directly after startup, you can customize a class to implement the ApplicationRunner interface and rewrite the run method of the interface.

@Component  // 此类必须要交给spring管理才生效
public class ConsumerRunner implements Application{
    
    
	@Oberride
	public void run(ApplicationArgumers args) throws Exception{
    
    
		//代码
		System.out.println("需要在springBoot项目启动时执行的代码---");
	}
}
  • In the same project, multiple ApplicationRunner implementation classes can be defined.

    If there are multiple implementation classes and they need to be executed in a certain order at the same time, it can be achieved by adding @Order annotation to the implementation class or implementing the Ordered interface .

    SpringBoot will execute according to the value value in @Order from small to large. That is, the smaller the value, the higher the priority, and the smaller the value, the first to be loaded.

    Note: Values ​​can be negative.

Principle of automatic configuration

overview

Spring Boot integrates a large number of third-party services internally, provides default configuration, and the steps for the default configuration to take effect:

  • The @EnableAutoConfiguration annotation will go to all packages to find META-INF/spring.factories files, and read the names of all classes with EnableAutoConfiguration as the key. These classes are auto-configuration classes written in advance
  • These classes all declare the @Configuration annotation, and configure all the required instances in advance through the @Bean annotation
  • However, these configurations do not necessarily take effect, because there are @Conditional annotations, which will only take effect when certain conditions are met
  • Only the relevant dependencies (starters) need to be introduced, the conditions required by the above configuration are met, and the automatic configuration takes effect
  • If you configure related beans yourself, it will override the default auto-configured beans
  • You can also override the properties in the automatic configuration by configuring the application.properties(yml) file

The reason why Spring Boot can be developed quickly is that there are many built-in default configurations of third-party components. The steps are as follows:

  1. use launcher

    If you don't want to configure it yourself, you only need to introduce the starter dependency, and you don't have to worry about the dependency version, because as long as the stater (starter) provided by Spring Boot is introduced, the dependency and version will be automatically managed.

  2. Replace the default configuration

    The configuration of SpringBoot will have default properties, and these properties can be overridden by modifying the application.properties file.

Key Notes

@Conditional

@Condition is a condition judgment function added in Spring 4.0. Through this function, selective creation of Bean operations can be realized.

@Conditional is marked on the configuration class or on the method of the configuration class. It is used in conjunction with @Configuration. When the conditions specified by @Conditional are met, the content in the configuration class will take effect

SpringBoot common condition annotations:

  • @ConditionalOnBean : The specified Bean exists in the container
  • @ConditionalOnMissingBean : The specified bean does not exist in the container
  • @ConditionalOnProperty : Whether the specified property in the system has the specified value
  • @ConditionalOnClass : There is a specified class in the system
  • @ConditionalOnMissingClass: The specified class does not exist in the system
  • @ConditionalOnExpression : Satisfy the SpEL expression specification
  • @ConditionalOnSingleCandidate : There is only one specified bean in the container, or this bean is the preferred bean
  • @ConditionalOnResource: Whether the specified resource file exists in the class path
  • @ConditionalOnWebApplication : the current web environment
  • @ConditionalOnNotWebApplication : Currently not a web environment
  • @ConditionalOnJava: Whether the java version of the system meets the requirements

Example:

User class

@Data
public class User {
    
    
    private String username;
    private Integer age;
}

configuration class

@Configuration
@ConditionalOnProperty(value = "user.enable")	// 配置文件存在该配置项时该配置类才生效
public class UserConfig {
    
    
    @Bean
    public User user(){
    
    
        User user = new User();
        user.setUsername("tom");
        user.setAge(18);
        return user;
    }
}

Add the following configuration to the configuration file:

user:
  enable: true

Add test case

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTests {
    
    
    
    @Autowired
    private User user;
    @Test
    public void testUser(){
    
    
        System.out.println(user);
    }
}

SpringBoot automatic configuration flow chart

insert image description here

When using it, you only need to introduce the corresponding starter. The starter is an indicator signal. After the dependency is introduced, the corresponding conditions are met, and the corresponding Bean will be registered.

@Import

reference:

  • https://blog.csdn.net/weixin_44360895/article/details/112758122
  • https://blog.csdn.net/mamamalululu00000000/article/details/86711079

@Import annotation: Import the class into the Spring IOC container

There are many ways to add class to IOC container management, such as @Bean, @Component, etc. @Import is another way, which is faster.

Three methods are supported:

  • Configuration classes with @Configuration (only configuration classes can be imported before version 4.2, and ordinary classes can also be imported after version 4.2)
  • Implementation of ImportSelector
  • Implementation of ImportBeanDefinitionRegistrar

Main usage:

  • Fill in the class array directly

    @Configuration
    @Import({
          
          User.class})   // 大括号中可以添加多个类,使用逗号分隔,例如 {User.class,UserInfo.class}
    public class UserConfig {
          
          }
    
  • ImportSelector method (the bottom layer of Spring Boot uses a lot of methods)

    // 自定义ImportSelector
    public class MyImportSelector implements ImportSelector {
          
          
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
          
          
            // 返回的是需要加载的类名数组  注意这里需要的是类的全路径
            return new String[]{
          
          "com.itheima.redis.entity.User"};
        }
    }
    
    @Configuration
    @Import(MyImportSelector.class)
    public class UserConfig {
          
          }
    
  • ImportBeanDefinitionRegistrar method

    This method is similar to the ImportSelector method, but this method can customize the name of the Bean in the container

    // 自定义ImportBeanDefinitionRegistrar
    public class TestImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
          
          
        @Override
        public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
          
          
            RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestD.class);
            //自定义注册bean
            registry.registerBeanDefinition("testD1111",rootBeanDefinition);
        }
    }
    
    @Import({
          
          TestImportBeanDefinitionRegistrar.class})
    @Configuration
    public class ImportConfig {
          
          }
    
  • Note: All three usage methods can be used in one @Import. It should be noted that in the class array method and ImportSelector method, the bean name in the IOC container is the fully qualified class name of the class, while the ImportBeanDefinitionRegistrar method is a custom name

@SpringBootApplication

flow chart

insert image description here

view source code

insert image description here

There are 3 key notes:

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

@SpringBootConfiguration

source code:

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@Indexed
public @interface SpringBootConfiguration {
    
    
    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

There is a @Configuration annotation on this annotation. The function of the @Configuration annotation is to declare that the current class is a configuration class, and then Spring will automatically scan to the class with @Configuration added and read the configuration information in it.

@SpringBootConfiguration is to declare that the current class is the configuration class of the SpringBoot application.

@EnableAutoConfiguration

source code:

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({
    
    AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    
    
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {
    
    };

    String[] excludeName() default {
    
    };
}

With help @Import(AutoConfigurationImportSelector.class), @EnableAutoConfigurationit can help Spring Boot applications to load all eligible @Configurationconfigurations into the IOC container created and used by the current Spring Boot.

  1. AutoConfigurationImportSelectorSource code, view selectImportsmethod:

    insert image description here

  2. Continue to follow up the getAutoConfigurationEntry method

    insert image description here

  3. getCandidateConfigurationsThere is a hint in the method :

    insert image description here

  4. Follow up loadFactoryNamesmethod:

    insert image description here

  5. You can see that the configuration is loaded from this location:

    insert image description here

  6. find the configuration file

    insert image description here

    There is automatic configuration here:

    insert image description here

    A large number of third-party middleware configuration classes are built into the automatic configuration package:

insert image description here

Summary: @EnableAutoConfigurationSearch all configuration files from the classpath META-INF/spring.factories, and org.springframework.boot.autoconfigure.EnableAutoConfiguration instantiate the corresponding configuration items into the corresponding IOC container configuration class in the form of JavaConfig marked with @Configuration through reflection, and then summarize them into one, and load it into the IOC container.

@ComponentScan

Turn on component scanning. Provides <context:component-scan>a role similar to the label

Specify the packages to scan through the basePackageClasses or basePackages properties. If these attributes are not specified, the package and subpackages will be scanned starting from the package where the class that declares this annotation is located

The class declared by the @SpringBootApplication annotation is the startup class where the main function is located, so the scanned package is the package where the class is located and its sub-packages. Therefore, the general startup class will be placed in a previous package directory

SpringBoot monitoring

Actuator

concept

SpringBoot has its own monitoring function Actuator, which can help monitor the internal operation of the program, such as monitoring status, Bean loading status, configuration properties, log information, etc.; at the same time, it can also manage applications through Actuator, such as doing a shutdown function through Actuator (default is not enabled), and can also adjust the log during operation.

Endpoints: endpoints

Endpoints can be understood as a functional module, which can monitor Spring Boot applications and even interact with Spring Boot (such as reading information, closing applications, etc.). Spring Boot has many built-in Endpoints, the most important Endpoints is health, which is the health check module.

Actuator endpoint description

endpoint illustrate enabled by default Default HTTP Default JMX
auditevents Exposes audit event information for the current application Y N Y
beans Displays information about beans from the Spring loC container Y N Y
caches show cache in app Y N Y
conditions Shows the evaluation and configuration conditions of an auto-configuration class, and shows why they match or do not match Y N Y
configprops Display the property configuration information of the current project (configured through @ConfigurationProperties) Y N Y
env Display the current Spring application environment configuration properties (ConfigurableEnvironment) Y N Y
flyway Displays information about migrations that have been applied to the flyway database Y N Y
health Display the current application health status Y Y Y
httptrace Display the latest tracking information (the default is the latest 100 HTTP requests) Y N Y
info Display current application information Y Y Y
loggers Display and update the configuration of the loggers in the application Y N Y
liquidbase Displays information about migrations that have been applied to the liquibase database Y N Y
metrics Displays the various "metrics" indicators currently configured Y N Y
mappings Display the mapping path information configured by @RequestMapping (@GetMapping and @PostMapping, etc.) Y N Y
scheduledtasks Display the currently applied scheduling task plan Y N Y
sessions Allows retrieving and deleting user sessions from the session repository supported by Spring Session, but Spring Session does not yet support responsive web applications Y N Y
shutdown Allows the current application to be gracefully shut down (this endpoint is not enabled by default) N N Y
threaddump show thread pump Y N Y
heapdump Return the Heap Dump file in HPROF format Y N N/A
prometheus Return information that can be crawled by Prometheus Y N N/A

Notice:

  • The shutdown endpoint is not enabled by default
  • Only health and info can be accessed through http by default

quick start

dependent coordinates

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

If you want to see more information, configure it in the configuration file:

management:
  endpoint:
    health:
      show-details: always
  endpoints:
    web:
      exposure:
        include: "*"

Actuator monitoring interface:

http://localhost:8080/actuator/beans

http://localhost:8080/actuator/env

http://localhost:8080/actuator/mappings

Specific and detailed explanation:

path describe
/beans Describe all beans in the application context and their relationships
/env Get all environment properties
/env/{name} Get a specific environment property value by name
/health Report the health indicators of the application, these values ​​​​are provided by the implementation class of HealthIndicator
/info Get the custom information of the application, which is provided by the attributes starting with info
/mappings Describe all URI paths and their mapping relationship with controllers (including Actuator endpoints)
/metrics Report various application metrics such as memory usage and HTTP request counts
/metrics/{name} Reports the application metric for the specified name
/trace Provides basic HTTP request tracking information (timestamps, HTTP headers, etc.)

Detailed configuration of Actuator

management:
  server:
    # Actuator的管理端口号,默认跟服务端口号(server.port)一致
    port: 8085
  endpoint:
    health:
      # 是否开启health端点,默认为true
      enabled: true
      # 展示健康检查中所有指标的详细信息
      show-details: always
  endpoints:
    # web:http方式
    web:
      exposure:
        # 暴露可以通过web访问的端点。默认"health,info",用 * 可以包含全部端点
        include: "*"
        # 不暴露的端点
        exclude: 
      # 自定义监控路径前缀。默认 /actuator
      base-path: /actuator
      # 修改端点的访问路径(映射),例如将 /beans 更改为 /request_beans
      path-mapping:
        beans: request_beans
    # 所有端点是否默认启动,默认true。若设置为false,则默认情况下所有端点都不启用,此时需要按需启用端点
    enabled-by-default: true

Spring Boot Admin

Overview and Quick Start

Actuator's monitoring content is detailed enough, but the readability is relatively poor, so you can use Spring Boot Admin to provide a visual interface to view information. Spring Boot Admin is an open source community project provided by a third party for managing and monitoring SpringBoot applications.

Source code library: https://github.com/codecentric/spring-boot-admin

Spring Boot Admin has two roles, client (Client) and server (Server):

  • The application registers with the Spring Boot Admin Server as a Spring Boot Admin Client

  • The interface of Spring Boot Admin Server will display the monitoring information of Spring Boot Admin Client

The development steps are as follows :

admin-server

  1. Create the admin-server module

  2. Import dependency coordinates admin-starter-server

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.3.0</version>
        </dependency>
    
  3. Mark the @EnableAdminServer annotation on the startup class to enable Admin monitoring

  4. Configuration related information

    server:
      port: 8888
    
  5. Start the server service, visit: http://localhost:8888/#/applications

admin-client : The project created by yourself is the so-called client side

  1. Create the admin-client module

  2. Import dependency coordinates admin-starter-client

    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>spring-boot-admin-starter-client</artifactId>
        <version>2.3.0</version>
    </dependency>
    
  3. Configuration related information: server address, etc.

    spring:
      boot:
        admin:
          client:
            url: http://localhost:8888
    management:
      endpoint:
        health:
          show-details: always
      endpoints:
        web:
          exposure:
            include: "*"
    
  4. Start the client service

Detailed configuration of Admin Server

Reference: https://www.jianshu.com/p/b0528b52772c

spring:
  boot:
    admin:
      # server端的访问路径。默认为 /
      context-path: /
      monitor:
        # 更新client端状态的时间间隔,默认为10000,单位是毫秒
        period: 10000
        # client端状态的生命周期,该生命周期内不会更新client状态,默认为100000,单位是毫秒
        status-lifetime: 100000
        # 查询client状态信息时的连接超时时间,默认为2000,单位是毫秒
          # 如果2秒内没有获取到client的状态信息,则认为连接已经断开
        connect-timeout: 2000
        # 查询client状态信息时的读取超时时间,默认为2000,单位是毫秒(如果2秒内没有获取到client的状态信息,则认为读取失败)
        read-timeout: 2000
      # 要被过滤掉的元数据(当与正则表达式相匹配时,这些数据会在输出的json数据中过滤掉)
        # 默认值是".password", ".secret",".∗secret", ".key", ".",".token", ".credentials.", ".*vcap_services", ".credentials.", ".∗vcap services"	
      metadata-keys-to-sanitize:
      # 要获取的client的端点信息
        # 默认是 "health", "env", "metrics", "httptrace:trace", "threaddump:dump", "jolokia", "info", "logfile", "refresh", "flyway", "liquibase", "heapdump", "loggers", "auditevents"	
      probed-endpoints: 
      instance-proxy:
        # 向client发起请求时不会被转发的headers信息。默认值是"Cookie", "Set-Cookie", "Authorization"
        ignored-headers: 
      ui:
        # 在导航栏中显示的brand值
        brand: 
        # 显示的页面标题。默认是"Spring Boot Admin"
        title: 

Detailed configuration of Admin Client

Reference: https://www.jianshu.com/p/b0528b52772c

spring:
  boot:
    admin:
      client:
        # 是否启用spring boot Admin客户端,默认为true
        enabled: true
        # 要注册的Admin Server端的url地址。如果要同时在多个server端口注册,则用逗号分隔各个server端的url地址
        url: http://localhost:8888
        # server端获取client信息的路径,默认情况下server通过访问/instances请求来获取到client端的信息。(client端向server端注册,注册成功后server端会给该client创建一个唯一的clientID值。当server端需要获取client的信息,比如health信息时,server端会发送http://IP:PORT/instances/clientID/actuator/health即可,这里的http://IP:PORT是client所在服务器的IP地址,instances就是该属性的值)
        api-path: instances
        # 如果server端需要进行认证时,该属性用于配置用户名
        username: user
        # 如果server端需要进行认证时,该属性用于配置密码
        password: 123456
        # 注册时间间隔,默认10000,单位是毫秒(client通过持续不断地向server端进行注册来保持client端与server端的连接)
        period: 10000
        # 注册连接超时时间,默认5000,单位是毫秒。当client向server进行注册时,如果5秒钟没有注册完成则认为本次注册失败
        connect-timeout: 5000
        # 注册读取超时,默认5000,单位是毫秒
        read-timeout: 5000
        # 是否开启自动注册,默认为true
        auto-registration: true
        # 是否开启自动注销,如果服务端运行在云平台,默认值是true
        auto-deregistration: null
        # 默认为true,client只会在一个server端进行注册(按照spring.boot.admin.client.url中设置的server的顺序),如果该server端宕机,会自动在下一个server端进行注册。如果该属性值为false,则会在所有的server端进行注册
        egister-once: true
        instance:
          # 注册的management-url,如果可用的url不同的话,可以重写该值。
          	# 默认该属性值与management-base-url 和 management.context-path两个属性值有关
          management-url:
          # 用于计算management-url的基本URL。该路径值在运行时进行获取并赋值给 base url
          	# 默认该属性值与management.port, service-url 以及server.servlet-path有关
          management-base-url:
          # 用于计算service-url的基本URL。该路径值在运行时进行获取并赋值给 base url
          service-base-url:
          # 注册的health-url地址,如果可用的url不同可以重写该值
          health-url:
          # 注册的service-url值
          service-url: http://192.168.0.66:22586
          # 客户端工程的名字。默认值是配置的spring.application.name的值	
          name:
          # 是否使用注册的ip地址来取代上述各个url中hostname的值,默认为false
          prefer-ip: true

Develop your own Starter launcher

Starters generally spring-boot-starter-start with , which is generally the official naming method of Spring.

Launchers developed by other businesses are named like this:XXX-boot-starter

The launcher is generally an empty shell with no code in it and is mainly used to manage dependencies

Development steps:

  1. Create a starter project, example: test-hello-spring-boot-starter

  2. Create an automatic configuration project, example: test-spring-boot-autoconfigure

    • (1) Add basic springboot dependencies (because you need to use annotations such as @Bean)

      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.1.3.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
      </parent>
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter</artifactId>
          </dependency>
      </dependencies>
      
    • (2) Define the automatic configuration class, example: define HelloTemplate as a Bean in the configuration class

      @Configuration
      public class HelloAutoConfiguration {
              
              
      
          @Bean   //实例化HelloTemplate,交给Spring IOC 容器管理
          public HelloTemplate helloTemplate(){
              
              
              return new HelloTemplate();
          }
      }
      
    • (3) Create a META-INF directory under resources, create a spring.factories file under the META-INF directory, and edit the configuration class (HelloAutoConfiguration) to be scanned in spring.factories, so that spring will scan HelloAutoConfiguration

      # 第一行固定写法,第二行这个是我们写的配置类的类名全路径 这样spring就能扫描到了
      org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      com.itheima.hellospringbootdemo.util.HelloAutoConfiguration
      
  3. Add the dependencies of the automatic configuration project to the pom file of the starter project

    <dependencies>
        <dependency>
            <groupId>com.test</groupId>
            <artifactId>test-spring-boot-autoconfigure</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    
  4. Add the dependencies of the stater project in other projects, and you can use @Autowired to use the Bean injected into the Spring container in the automatic configuration project

Deploy the SpringBoot project

project packaging

In the SpringBoot project, it is all done by packaging the project into a jar package and then running it directly (because tomcat is built-in)

  1. Prepare a developed SpringBoot project, because it is a SpringBoot project, so there must be a startup class

  2. In the pom file in the project to be packaged, add the following content

    <build>
        <!--finalName 可以不写,写了就是要打包的项目的名称 -->
        <finalName>demo</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
  3. Find the maven area on the right side of the idea, find the project you want to package, click clean, and clear the cache, as shown in the figure

    insert image description here

    If you click test, all test cases under test/java will be run aside, and the following process will be executed after all test cases pass. The process here is that the next step will include the previous step.

    If you don't want to run the test case when packaging, there are two ways to skip it:

    • Method 1: You can add the following settings in pom:

      <properties>
          <!--打包时跳过测试用例-->
          <skipTests>true</skipTests>
      </properties>
      
    • Method 2: Configure in IDEA as follows

      insert image description here

  4. Click on the package to carry out the packaging operation, and finally display BUILD SUCCESSmeans that the packaging is successful

    Note: If the project has custom dependencies, you need to click install first to install the dependent package to the local warehouse; otherwise, if you click the package directly, an error such as class not found will be reported

  5. In the target directory of the project on the left side of the idea, you can find the jar package you just created

  6. Enter cmd in the address bar of the jar package folder, open the command window, enter in the command line java -jar 项目名.jar, and press Enter to start the application

Spring Boot multi-environment configuration switching

Generally in a project, there are always multiple environments. For example: development environment -> test environment -> pre-release environment -> production environment.

The configuration files on each environment are always different, and even the environment of each developer in the development environment may be a little different.

In Spring Boot, the file name of the multi-environment configuration needs to meet the format of application-{profile}.yml or application-{profile}.properties, where {profile} corresponds to the environment, for example:

  • application-dev.yml: development environment
  • application-test.yml: test environment
  • application-prod.yml: production environment

Common ways to configure the environment:

  • Way 1: application.ymlConfigure directly in:

    spring:
      profiles:
        active: dev
    
  • Method 2: Specify the configuration in IDEA to take effect:

    insert image description here

  • Method 3: Add parameters at startup to specify which configuration to use

    # 使用测试环境配置文件
    java -jar xxx.jar --spring.profiles.active=test
    

Spring Boot configuration loading order

If Spring Boot finds the same configuration in a higher-priority location, it ignores the lower-level configuration. If different configurations can take effect at the same time.

According to Spring Boot's documentation, the priority of configuration usage is from high to , as follows:

  1. command line parameters
  2. Java system parameters obtained by System.getProperties()
  3. operating system environment variables
  4. JNDI properties from java:comp/env
  5. "random.*" properties generated via RandomValuePropertySource
  6. Properties file outside the application Jar file (application-{profile}.properties/yml)
  7. Properties file inside the application Jar file (application-{profile}.properties/yml)
  8. Properties file outside the application Jar file (application.properties/yml)
  9. Properties file inside the application Jar file (application.properties/yml)
  10. A property file declared via the "@PropertySource" annotation in the application configuration Java class (a Java class containing the "@Configuration" annotation)
  11. Default properties declared via "SpringApplication.setDefaultProperties"

Spring Boot loads external configuration files

  • Method 1: Specify by environment variable spring.config.location

    Note: After using the location parameter to specify the configuration file, the default configuration file (application.properties or application.yml) of the project will be invalidated, and Spring Boot will only load the specified external configuration file

    java -jar springbootdemo-0.0.1-SNAPSHOT.jar --spring.config.location=./my-application.yml
    
  • Method 2: Specify by environment variable spring.config.additional-location

    Note: Using the additional-location parameter will not invalidate the default configuration file of the project. The external configuration file will take effect together with the default configuration file of the project to form a complementary configuration, and its priority is higher than that of all default configuration files

    java -jar springbootdemo-0.0.1-SNAPSHOT.jar --spring.config.additional-location=./my-application.yml
    

Guess you like

Origin blog.csdn.net/footless_bird/article/details/128232709