主頁 > 軟體設計 > 位元組總監肝了一周總結的SpringBoot實戰教程,太實用了!

位元組總監肝了一周總結的SpringBoot實戰教程,太實用了!

2020-11-24 19:56:45 軟體設計

天天在用SpringBoot,但有些SpringBoot的實用知識點卻不是很清楚!最近又對SpringBoot中的實用知識點做了個總結,相信對從Spring過渡到SpringBoot的朋友會很有幫助!

前言

首先我們來了解下為什么要有SpringBoot?

Spring作為J2EE的輕量級代替品,讓我們無需開發重量級的Enterprise JavaBean(EJB),通過依賴注入和面向切面編程,使用簡單的Java物件(POJO)即可實作EJB的功能,

雖然Spring的組件代碼是輕量級的,但它的配置卻是重量級的,即使后來Spring引入了基于注解的組件掃描和基于Java的配置,讓它看上去簡潔不少,但Spring還是需要不少配置,除此之外,專案的依賴管理也很麻煩,我們無法確保各個版本的依賴都能兼容,

為了簡化Spring中的配置和統一各種依賴的版本,SpringBoot誕生了!

簡介

SpringBoot從本質上來說就是Spring,它通過了一些自己的特性幫助我們簡化了Spring應用程式的開發,主要有以下三個核心特性:

  • 自動配置:對于很多Spring應用程式常見的應用功能,SpringBoot能自動提供相關配置,集成功能開發者僅需很少的配置,
  • 起步依賴:告訴SpringBoot需要什么功能,它就能引入對應的庫,無需考慮該功能依賴庫的版本問題,
  • Actuator:可以深入了解SpringBoot應用程式內部情況,比如創建了哪些Bean、自動配置的決策、應用程式的狀態資訊等,

開始使用

創建應用

創建SpringBoot應用的方式有很多種,這里使用最流行的開發工具IDEA來創建應用,

  • 首先通過File->New Project來創建一個專案;

  • 然后選擇通過Spring Initializr來創建一個SpringBoot應用;

  • 填寫好Maven專案的groupId和artifactId及選擇好Java版本;

  • 選擇好起步依賴,這里選擇的是開啟Web功能的起步依賴;

  • 選擇好專案的存放位置即可順利創建一個SpringBoot應用,

查看應用

SpringBoot實戰教程原始碼地址:點擊即可免費獲取

專案結構

一個新創建的SpringBoot應用基本結構如下,

mall-tiny-boot
├─pom.xml # Maven構建檔案
└─src
   ├─main
   │  ├─java
   │  │  └─MallTinyApplication.java # 應用程式啟動類
   │  └─resources
   │     └─application.yml # SpringBoot組態檔
   └─test
       └─java
           └─MallTinyApplicationTests.java # 基本的集成測驗類

應用啟動類

MallTinyApplication在SpringBoot應用中有配置和引導的作用,通過@SpringBootApplication注解開啟組件掃描和自動配置,通過SpringApplication.run()引導應用程式啟動;

//開啟組件掃描和應用裝配
@SpringBootApplication
public class MallTinyApplication {

    public static void main(String[] args) {
        //負責引導應用程式啟動
        SpringApplication.run(MallTinyApplication.class, args);
    }

}

@SpringBootApplication注解是三個注解的結合體,擁有以下三個注解的功能:

  • @Configuration:用于宣告Spring中的Java配置;

  • @ComponentScan:啟用組件掃描,當我們宣告組件時,會自動發現并注冊為Spring應用背景關系中的Bean;

  • @EnableAutoConfiguration:開啟SpringBoot自動配置功能,簡化配置撰寫,

測驗應用

可以使用@RunWith@SpringBootTest來創建Spring應用背景關系,通過@Test注解來宣告一個測驗方法,

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class MallTinyApplicationTests {
    @Autowired
    private PmsBrandService pmsBrandService;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testMethod() {
        List<PmsBrand> brandList = pmsBrandService.listAllBrand();
        log.info("testMethod:{}", brandList);
    }

}

撰寫應用配置

當我們需要微調自動配置的引數時,可以在application.yml檔案中進行配置,比如微調下埠號,

server:
  port: 8088

專案構建程序

SpringBoot專案可以使用Maven進行構建,首先我們需要繼承spring-boot-starter-parent這個父依賴,父依賴可以控制所有SpringBoot官方起步依賴的版本,接下來當我們使用官方起步依賴時,就不用指定版本號了,我們還需要使用SpringBoot的插件,該插件主要用于將應用打包為可執行Jar,

<?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.macro.mall</groupId>
    <artifactId>mall-tiny-boot</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>mall-tiny-boot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <skipTests>true</skipTests>
    </properties>
    
    <!--繼承SpringBoot父專案,控制所有依賴版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <!--SpringBoot起步依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <!--SpringBoot插件,可以把應用打包為可執行Jar-->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

使用起步依賴

使用起步依賴的好處

在使用起步依賴之前,我們先來了解下使用起步依賴的好處,當我們使用SpringBoot需要整合Web相關功能時,只需在pom.xml中添加一個起步依賴即可,

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

如果是Spring專案的話,我們需要添加很多依賴,還需要考慮各個依賴版本的兼容性問題,是個相當麻煩的事情,

指定基于功能的依賴

當我們需要開發一個Web應用,需要使用MySQL資料庫進行存盤,使用Swagger生成API檔案,添加如下起步依賴即可,需要注意的是只有官方的起步依賴不需要指定版本號,其他的還是需要自行指定的,

<dependencies>
    <!--SpringBoot 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>
    <!--MyBatis分頁插件-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.10</version>
    </dependency>
    <!--集成druid連接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <!--Mysql資料庫驅動-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
    </dependency>
    <!--springfox swagger官方Starter-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
</dependencies>

覆寫起步依賴中的庫

其實起步依賴和你平時使用的依賴沒什么區別,你可以使用Maven的方式來排除不想要的依賴,比如你不想使用tomcat容器,想使用undertow容器,可以在Web功能依賴中排除掉tomcat,

<dependencies>
    <!--SpringBoot Web功能起步依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <!--排除tomcat依賴-->
            <exclusion>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <groupId>org.springframework.boot</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <!--undertow容器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
</dependencies>

使用自動配置

SpringBoot的自動配置是一個運行時(更準確地說,是應用程式啟動時)的程序,考慮了眾多因素,才決定Spring配置應該用哪個,不該用哪個,

舉個例子,當我們使用Spring整合MyBatis的時候,需要完成如下幾個步驟:

  • 根據資料庫連接配置,配置一個dataSource物件;

  • 根據dataSource物件和SqlMapConfig.xml檔案(其中包含mapper.xml檔案路徑和mapper介面路徑配置),配置一個sqlSessionFactory物件,

當我們使用SpringBoot整合MyBatis的時候,會自動創建dataSource和sqlSessionFactory物件,只需我們在application.yml和Java配置中添加一些自定義配置即可,

application.yml中配置好資料庫連接資訊及mapper.xml檔案路徑,

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

mybatis:
  mapper-locations:
    - classpath:mapper/*.xml
    - classpath*:com/**/mapper/*.xml

使用Java配置,配置好mapper介面路徑,

/**
 * MyBatis配置類
 * Created by macro on 2019/4/8.
 */
@Configuration
@MapperScan("com.macro.mall.tiny.mbg.mapper")
public class MyBatisConfig {
}

使用自動配置以后,我們整合其他功能的配置大大減少了,可以更加專注程式功能的開發了,

SpringBoot實戰教程原始碼地址:點擊即可免費獲取

自定義配置

自定義Bean覆寫自動配置

雖然自動配置很好用,但有時候自動配置的Bean并不能滿足你的需要,我們可以自己定義相同的Bean來覆寫自動配置中的Bean,

例如當我們使用Spring Security來保護應用安全時,由于自動配置并不能滿足我們的需求,我們需要自定義基于WebSecurityConfigurerAdapter的配置,這里我們自定義了很多配置,比如將基于Session的認證改為使用JWT令牌、配置了一些路徑的無授權訪問,自定義了登錄介面路徑,禁用了csrf功能等,

/**
 * SpringSecurity的配置
 * Created by macro on 2018/4/26.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        List<String> urls = ignoreUrlsConfig.getUrls();
        String[] urlArray = ArrayUtil.toArray(urls, String.class);
        httpSecurity.csrf()// 由于使用的是JWT,我們這里不需要csrf
                .disable()
                .sessionManagement()// 基于token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,urlArray) // 允許對于網站靜態資源的無授權訪問
                .permitAll()
                .antMatchers("/admin/login")// 對登錄注冊要允許匿名訪問
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域請求會先進行一次options請求
                .permitAll()
                .anyRequest()// 除上面外的所有請求全部需要鑒權認證
                .authenticated();
        // 禁用快取
        httpSecurity.headers().cacheControl();
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定義未授權和未登錄結果回傳
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        //獲取登錄用戶資訊
        return username -> {
            AdminUserDetails admin = adminService.getAdminByUsername(username);
            if (admin != null) {
                return admin;
            }
            throw new UsernameNotFoundException("用戶名或密碼錯誤");
        };
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

自動配置微調

有時候我們只需要微調下自動配置就能滿足需求,并不需要覆寫自動配置的Bean,此時我們可以在application.yml屬性檔案中進行配置,

比如微調下應用運行的埠,

server:
  port: 8088

比如修改下資料庫連接資訊,

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

讀取組態檔的自定義屬性

有時候我們會在屬性檔案中自定義一些屬性,然后在程式中使用,此時可以將這些自定義屬性映射到一個屬性類里來使用,

比如說我們想給Spring Security配置一個白名單,訪問這些路徑無需授權,我們可以先在application.yml中添添加如下配置,

secure:
  ignored:
    urls:
      - /
      - /swagger-ui/
      - /*.html
      - /favicon.ico
      - /**/*.html
      - /**/*.css
      - /**/*.js
      - /swagger-resources/**
      - /v2/api-docs/**

之后創建一個屬性類,使用@ConfigurationProperties注解配置好這些屬性的前綴,再定義一個urls屬性與屬性檔案相對應即可,

/**
 * 用于配置白名單資源路徑
 * Created by macro on 2018/11/5.
 */
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "secure.ignored")
public class IgnoreUrlsConfig {

    private List<String> urls = new ArrayList<>();

}

Actuator

SpringBoot Actuator的關鍵特性是在應用程式里提供眾多Web端點,通過它們了解應用程式運行時的內部狀況,

端點概覽

Actuator提供了大概20個端點,常用端點路徑及描述如下:

路徑請求方式描述
/beansGET描述應用程式背景關系里全部的Bean,以及它們之間關系
/conditionsGET描述自動配置報告,記錄哪些自動配置生效了,哪些沒生效
/envGET獲取全部環境屬性
/env/{name}GET根據名稱獲取特定的環境屬性
/mappingsGET描述全部的URI路徑和控制器或過濾器的映射關系
/configpropsGET描述配置屬性(包含默認值)如何注入Bean
/metricsGET獲取應用程式度量指標,比如JVM和行程資訊
/metrics/{name}GET獲取指定名稱的應用程式度量值
loggersGET查看應用程式中的日志級別
/threaddumpGET獲取執行緒活動的快照
/healthGET報告應用程式的健康指標,這些值由HealthIndicator的實作類提供
/shutdownPOST關閉應用程式
/infoGET獲取應用程式的定制資訊,這些資訊由info打頭的屬性提供

查看配置明細

  • 直接訪問根端點,可以獲取到所有端點訪問路徑,根端點訪問地址:http://localhost:8088/actuator

  • SpringBoot實戰教程原始碼地址:點擊即可免費獲取

{
    "_links": {
        "self": {
            "href": "http://localhost:8088/actuator",
            "templated": false
        },
        "beans": {
            "href": "http://localhost:8088/actuator/beans",
            "templated": false
        },
        "caches-cache": {
            "href": "http://localhost:8088/actuator/caches/{cache}",
            "templated": true
        },
        "caches": {
            "href": "http://localhost:8088/actuator/caches",
            "templated": false
        },
        "health": {
            "href": "http://localhost:8088/actuator/health",
            "templated": false
        },
        "health-path": {
            "href": "http://localhost:8088/actuator/health/{*path}",
            "templated": true
        },
        "info": {
            "href": "http://localhost:8088/actuator/info",
            "templated": false
        },
        "conditions": {
            "href": "http://localhost:8088/actuator/conditions",
            "templated": false
        },
        "configprops": {
            "href": "http://localhost:8088/actuator/configprops",
            "templated": false
        },
        "env": {
            "href": "http://localhost:8088/actuator/env",
            "templated": false
        },
        "env-toMatch": {
            "href": "http://localhost:8088/actuator/env/{toMatch}",
            "templated": true
        },
        "loggers": {
            "href": "http://localhost:8088/actuator/loggers",
            "templated": false
        },
        "loggers-name": {
            "href": "http://localhost:8088/actuator/loggers/{name}",
            "templated": true
        },
        "heapdump": {
            "href": "http://localhost:8088/actuator/heapdump",
            "templated": false
        },
        "threaddump": {
            "href": "http://localhost:8088/actuator/threaddump",
            "templated": false
        },
        "metrics-requiredMetricName": {
            "href": "http://localhost:8088/actuator/metrics/{requiredMetricName}",
            "templated": true
        },
        "metrics": {
            "href": "http://localhost:8088/actuator/metrics",
            "templated": false
        },
        "scheduledtasks": {
            "href": "http://localhost:8088/actuator/scheduledtasks",
            "templated": false
        },
        "mappings": {
            "href": "http://localhost:8088/actuator/mappings",
            "templated": false
        }
    }
}
  • 通過/beans端點,可以獲取到Spring應用背景關系中的Bean的資訊,比如Bean的型別和依賴屬性等,訪問地址:http://localhost:8088/actuator/beans

{
 "contexts": {
  "application": {
   "beans": {
    "sqlSessionFactory": {
     "aliases": [],
     "scope": "singleton",
     "type": "org.apache.ibatis.session.defaults.DefaultSqlSessionFactory",
     "resource": "class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]",
     "dependencies": [
      "dataSource"
     ]
    },
    "jdbcTemplate": {
     "aliases": [],
     "scope": "singleton",
     "type": "org.springframework.jdbc.core.JdbcTemplate",
     "resource": "class path resource [org/springframework/boot/autoconfigure/jdbc/JdbcTemplateConfiguration.class]",
     "dependencies": [
      "dataSource",
      "spring.jdbc-org.springframework.boot.autoconfigure.jdbc.JdbcProperties"
     ]
    }
   }
  }
 }
}
  • 通過/conditions端點,可以獲取到當前應用的自動配置報告,positiveMatches表示生效的自動配置,negativeMatches表示沒有生效的自動配置,

{
 "contexts": {
  "application": {
   "positiveMatches": {
    "DruidDataSourceAutoConfigure": [{
     "condition": "OnClassCondition",
     "message": "@ConditionalOnClass found required class 'com.alibaba.druid.pool.DruidDataSource'"
    }]
   },
   "negativeMatches": {
    "RabbitAutoConfiguration": {
     "notMatched": [{
      "condition": "OnClassCondition",
      "message": "@ConditionalOnClass did not find required class 'com.rabbitmq.client.Channel'"
     }],
     "matched": []
    }
   }
  }
 }
}
  • 通過/env端點,可以獲取全部配置屬性,包括環境變數、JVM屬性、命令列引數和application.yml中的屬性,

{
 "activeProfiles": [],
 "propertySources": [{
   "name": "systemProperties",
   "properties": {
    "java.runtime.name": {
     "value": "Java(TM) SE Runtime Environment"
    },
    "java.vm.name": {
     "value": "Java HotSpot(TM) 64-Bit Server VM"
    },
    "java.runtime.version": {
     "value": "1.8.0_91-b14"
    }
   }
  },
  {
   "name": "applicationConfig: [classpath:/application.yml]",
   "properties": {
    "server.port": {
     "value": 8088,
     "origin": "class path resource [application.yml]:2:9"
    },
    "spring.datasource.url": {
     "value": "jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai",
     "origin": "class path resource [application.yml]:6:10"
    },
    "spring.datasource.username": {
     "value": "root",
     "origin": "class path resource [application.yml]:7:15"
    },
    "spring.datasource.password": {
     "value": "******",
     "origin": "class path resource [application.yml]:8:15"
    }
   }
  }
 ]
}
  • 通過/mappings端點,可以查看全部的URI路徑和控制器或過濾器的映射關系,這里可以看到我們自己定義的PmsBrandControllerJwtAuthenticationTokenFilter的映射關系,

{
 "contexts": {
  "application": {
   "mappings": {
    "dispatcherServlets": {
     "dispatcherServlet": [{
      "handler": "com.macro.mall.tiny.controller.PmsBrandController#createBrand(PmsBrand)",
      "predicate": "{POST /brand/create}",
      "details": {
       "handlerMethod": {
        "className": "com.macro.mall.tiny.controller.PmsBrandController",
        "name": "createBrand",
        "descriptor": "(Lcom/macro/mall/tiny/mbg/model/PmsBrand;)Lcom/macro/mall/tiny/common/api/CommonResult;"
       },
       "requestMappingConditions": {
        "consumes": [],
        "headers": [],
        "methods": [
         "POST"
        ],
        "params": [],
        "patterns": [
         "/brand/create"
        ],
        "produces": []
       }
      }
     }]
    }
   },
   "servletFilters": [{
    "servletNameMappings": [],
    "urlPatternMappings": [
     "/*",
     "/*",
     "/*",
     "/*",
     "/*"
    ],
    "name": "jwtAuthenticationTokenFilter",
    "className": "com.macro.mall.tiny.component.JwtAuthenticationTokenFilter"
   }]
  }
 }
}

查看運行時度量

  • 通過/metrics端點,可以獲取應用程式度量指標,不過只能獲取度量的名稱;

{
    "names": [
        "http.server.requests",
        "jvm.buffer.count",
        "jvm.buffer.memory.used",
        "jvm.buffer.total.capacity",
        "jvm.classes.loaded",
        "jvm.classes.unloaded",
        "jvm.gc.live.data.size",
        "jvm.gc.max.data.size",
        "jvm.gc.memory.allocated",
        "jvm.gc.memory.promoted",
        "jvm.gc.pause",
        "jvm.memory.committed",
        "jvm.memory.max",
        "jvm.memory.used",
        "jvm.threads.daemon",
        "jvm.threads.live",
        "jvm.threads.peak",
        "jvm.threads.states",
        "logback.events",
        "process.cpu.usage",
        "process.start.time",
        "process.uptime",
        "system.cpu.count",
        "system.cpu.usage"
    ]
}
  • 需要添加指標名稱才能獲取對應的值,比如獲取當前JVM使用的記憶體資訊,訪問地址:http://localhost:8088/actuator/metrics/jvm.memory.used

{
    "name": "jvm.memory.used",
    "description": "The amount of used memory",
    "baseUnit": "bytes",
    "measurements": [
        {
            "statistic": "VALUE",
            "value": 3.45983088E8
        }
    ],
    "availableTags": [
        {
            "tag": "area",
            "values": [
                "heap",
                "nonheap"
            ]
        },
        {
            "tag": "id",
            "values": [
                "Compressed Class Space",
                "PS Survivor Space",
                "PS Old Gen",
                "Metaspace",
                "PS Eden Space",
                "Code Cache"
            ]
        }
    ]
}
  • 通過loggers端點,可以查看應用程式中的日志級別資訊,可以看出我們把ROOT范圍日志設定為了INFO,而com.macro.mall.tiny包范圍的設定為了DEBUG,

{
 "levels": [
  "OFF",
  "ERROR",
  "WARN",
  "INFO",
  "DEBUG",
  "TRACE"
 ],
 "loggers": {
  "ROOT": {
   "configuredLevel": "INFO",
   "effectiveLevel": "INFO"
  },
  "com.macro.mall.tiny": {
   "configuredLevel": "DEBUG",
   "effectiveLevel": "DEBUG"
  }
 }
}
  • 通過/health端點,可以查看應用的健康指標,

{
    "status": "UP"
}

關閉應用

通過POST請求/shutdown端點可以直接關閉應用,但是需要將endpoints.shutdown.enabled屬性設定為true才可以使用,

{
    "message": "Shutting down, bye..."
}

定制Actuator

有的時候,我們需要自定義一下Actuator的端點才能滿足我們的需求,

  • 比如說Actuator有些端點默認是關閉的,我們想要開啟所有端點,可以這樣設定;

management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 比如說我們想自定義Actuator端點的基礎路徑,比如改為/monitor,這樣我們我們訪問地址就變成了這個:http://localhost:8088/monitor

management:
  endpoints:
    web:
      base-path: /monitor

常用起步依賴

起步依賴不僅能讓構建應用的依賴配置更簡單,還能根據提供給應用程式的功能將它們組織到一起,這里整理了一些常用的起步依賴,

官方依賴

<dependencies>
    <!--SpringBoot整合Web功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--SpringBoot整合Actuator功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--SpringBoot整合AOP功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <!--SpringBoot整合測驗功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--SpringBoot整合注解處理功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <!--SpringBoot整合Spring Security安全功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!--SpringBoot整合Redis資料存盤功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!--SpringBoot整合Elasticsearch資料存盤功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    <!--SpringBoot整合MongoDB資料存盤功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <!--SpringBoot整合AMQP訊息佇列功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    <!--SpringBoot整合Quartz定時任務功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
    <!--SpringBoot整合JPA資料存盤功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!--SpringBoot整合郵件發送功能依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
</dependencies>

第三方依賴

<dependencies>
    <!--SpringBoot整合MyBatis資料存盤功能依賴-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis-version.version}</version>
    </dependency>
    <!--SpringBoot整合PageHelper分頁功能依賴-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>${pagehelper-starter.version}</version>
    </dependency>
    <!--SpringBoot整合Druid資料庫連接池功能依賴-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>${druid.version}</version>
    </dependency>  
    <!--SpringBoot整合Springfox的Swagger API檔案功能依賴-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>${springfox-version}</version>
    </dependency>
    <!--SpringBoot整合MyBatis-Plus資料存盤功能依賴-->  
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>${mybatis-plus-version}</version>
    </dependency>
    <!--SpringBoot整合Knife4j API檔案功能依賴--> 
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>${knife4j-version}</version>
    </dependency>        
</dependencies>

SpringBoot實戰教程原始碼地址:點擊即可免費獲取

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/226905.html

標籤:其他

上一篇:先設計一個基本賬戶類,再通過繼承基本賬戶類設計一個儲蓄賬戶類,儲蓄賬戶 類中增加密碼、地址、最小余額和利率等成員變數,并增加一些銀行賬戶經常用到的成員函式。 要求: (1)類

下一篇:計算機網路安全C復習

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 面試突擊第一季,第二季,第三季

    第一季必考 https://www.bilibili.com/video/BV1FE411y79Y?from=search&seid=15921726601957489746 第二季分布式 https://www.bilibili.com/video/BV13f4y127ee/?spm_id_fro ......

    uj5u.com 2020-09-10 05:35:24 more
  • 第三單元作業總結

    1.前言 這應該是本學期最后一次寫作業總結了吧。總體來說,對作業的節奏也差不多掌握了,作業做起來的效率也更高了。雖然和之前的作業一樣,作業中都要用到新的知識,但是相比之前,更加懂得了如何利用工具以及資料。雖然之間卡過殼,但總體而言,這幾次作業還算完成的比較好。 2.作業程序總結 相比前兩個單元,此單 ......

    uj5u.com 2020-09-10 05:35:41 more
  • 北航OO(2020)第四單元博客作業暨課程總結博客

    北航OO(2020)第四單元博客作業暨課程總結博客 本單元作業的架構設計 在本單元中,由于UML圖具有比較清晰的樹形結構,因此我對其中需要進行查詢操作的元素進行了包裝,在樹的父節點中存盤所有孩子的參考。考慮到性能問題,我采用了快取機制,一次查詢后盡可能快取已經遍歷過的資訊,以減少遍歷次數。 本單元我 ......

    uj5u.com 2020-09-10 05:35:48 more
  • BUAA_OO_第四單元

    一、UML決議器設計 ? 先看下題目:第四單元實作一個基于JDK 8帶有效性檢查的UML(Unified Modeling Language)類圖,順序圖,狀態圖分析器 MyUmlInteraction,實際上我們要建立一個有向圖模型,UML中的物件(元素)可能與同級元素連接,也可與低級元素相連形成 ......

    uj5u.com 2020-09-10 05:35:54 more
  • 6.1邏輯運算子

    邏輯運算子 1. && 短路與 運算式1 && 運算式2 01.運算式1為true并且運算式2也為true 整體回傳為true 02.運算式1為false,將不會執行運算式2 整體回傳為false 03.只要有一個運算式為false 整體回傳為false 2. || 短路或 運算式1 || 運算式2 ......

    uj5u.com 2020-09-10 05:35:56 more
  • BUAAOO 第四單元 & 課程總結

    1. 第四單元:StarUml檔案決議 本單元采用了圖模型決議UML。 UML檔案可以抽象為圖、子圖、邊的邏輯結構。 在實作中,圖的節點包括類、介面、屬性,子圖包括狀態圖、順序圖等。 采用了三次遍歷UML元素的方法建圖,第一遍遍歷建點,第二、三次遍歷設定屬性、連邊,實作圖物件的初始化。這里借鑒了一些 ......

    uj5u.com 2020-09-10 05:36:06 more
  • 談談我對C# 多型的理解

    面向物件三要素:封裝、繼承、多型。 封裝和繼承,這兩個比較好理解,但要理解多型的話,可就稍微有點難度了。今天,我們就來講講多型的理解。 我們應該經常會看到面試題目:請談談對多型的理解。 其實呢,多型非常簡單,就一句話:呼叫同一種方法產生了不同的結果。 具體實作方式有三種。 一、多載 多載很簡單。 p ......

    uj5u.com 2020-09-10 05:36:09 more
  • Python 資料驅動工具:DDT

    背景 python 的unittest 沒有自帶資料驅動功能。 所以如果使用unittest,同時又想使用資料驅動,那么就可以使用DDT來完成。 DDT是 “Data-Driven Tests”的縮寫。 資料:http://ddt.readthedocs.io/en/latest/ 使用方法 dd. ......

    uj5u.com 2020-09-10 05:36:13 more
  • Python里面的xlrd模塊詳解

    那我就一下面積個問題對xlrd模塊進行學習一下: 1.什么是xlrd模塊? 2.為什么使用xlrd模塊? 3.怎樣使用xlrd模塊? 1.什么是xlrd模塊? ?python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫。 今天就先來說一下xl ......

    uj5u.com 2020-09-10 05:36:28 more
  • 當我們創建HashMap時,底層到底做了什么?

    jdk1.7中的底層實作程序(底層基于陣列+鏈表) 在我們new HashMap()時,底層創建了默認長度為16的一維陣列Entry[ ] table。當我們呼叫map.put(key1,value1)方法向HashMap里添加資料的時候: 首先,呼叫key1所在類的hashCode()計算key1 ......

    uj5u.com 2020-09-10 05:36:38 more
最新发布
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:20:47 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:20:25 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:20:17 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:20:10 more
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:19:44 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:19:07 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:18:57 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:18:49 more
  • 05單件模式

    #經典的單件模式 public class Singleton { private static Singleton uniqueInstance; //一個靜態變數持有Singleton類的唯一實體。 // 其他有用的實體變數寫在這里 //構造器宣告為私有,只有Singleton可以實體化這個類! ......

    uj5u.com 2023-04-19 08:42:51 more
  • 【架構與設計】常見微服務分層架構的區別和落地實踐

    軟體工程的方方面面都遵循一個最基本的道理:沒有銀彈,架構分層模型更是如此,每一種都有各自優缺點,所以請根據不同的業務場景,并遵循簡單、可演進這兩個重要的架構原則選擇合適的架構分層模型即可。 ......

    uj5u.com 2023-04-19 08:42:41 more