天天在用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個端點,常用端點路徑及描述如下:
路徑 | 請求方式 | 描述 |
---|---|---|
/beans | GET | 描述應用程序上下文裏全部的Bean,以及它們之間關係 |
/conditions | GET | 描述自動配置報告,記錄哪些自動配置生效了,哪些沒生效 |
/env | GET | 獲取全部環境屬性 |
/env/{name} | GET | 根據名稱獲取特定的環境屬性 |
/mappings | GET | 描述全部的URI路徑和控制器或過濾器的映射關係 |
/configprops | GET | 描述配置屬性(包含默認值)如何注入Bean |
/metrics | GET | 獲取應用程序度量指標,比如JVM和進程信息 |
/metrics/{name} | GET | 獲取指定名稱的應用程序度量值 |
loggers | GET | 查看應用程序中的日誌級別 |
/threaddump | GET | 獲取線程活動的快照 |
/health | GET | 報告應用程序的健康指標,這些值由HealthIndicator的實現類提供 |
/shutdown | POST | 關閉應用程序 |
/info | GET | 獲取應用程序的定製信息,這些信息由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路徑和控制器或過濾器的映射關係,這裏可以看到我們自己定義的PmsBrandController
和JwtAuthenticationTokenFilter
的映射關係。
{
"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實戰教程源碼地址:點擊即可免費獲取