1. Spring Boot簡介
Spring Boot的設計目的是用來簡化新Spring應用的初始搭建以及開發過程。SpringBoot所具備的特征有:
- 可以創建獨立的Spring應用程序,并且基于其Maven或Gradle插件,可以創建可執行的JARs和WARs
- 內嵌Tomcat或Jetty等Servlet容器
- 提供自動配置的“starter”項目對象模型(POMS)以簡化Maven配置
- 盡可能自動配置Spring容器
- 提供準備好的特性,如指標、健康檢查和外部化配置
- 絕對沒有代碼生成,不需要XML配置
Spring Boot官網:https://spring.io/projects/spring-boot/
Spring Boot啟動結構圖(圖片太大了,可單獨查看圖片):
Spring Boot啟動過程:
一路追蹤源碼:
SpringApplication.run()
// 先new對象,然后run
new SpringApplication(primarySources).run(args)
// new對象的構造方法
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
// 配置Source
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// 判斷是否為web環境
this.webApplicationType = WebApplicationType.deduceFromClasspath();
this.bootstrappers = new ArrayList<>(getSpringFactoriesInstances(Bootstrapper.class));
// 創建初始化構造器,加載spring.factories文件中ApplicationContextInitializer對應的所有類
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 創建應用監聽器,加載spring.factories文件中ApplicationListener對應的所有類
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 配置應用的主方法所在類
this.mainApplicationClass = deduceMainApplicationClass();
}
// run方法:運行Spring應用程序,創建并刷新新的應用程序上下文
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
// 應用啟動計時器開始計時
stopWatch.start();
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
configureHeadlessProperty();
// 獲取spring.factories文件中SpringApplicationRunListener對應的監聽器
SpringApplicationRunListeners listeners = getRunListeners(args);
// 廣播事件,應用啟動監聽器開始監聽
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 準備環境
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
configureIgnoreBeanInfo(environment);
// 應用啟動時的提示圖標,可以在resources下創建一個banner.txt來修改啟動時的打印信息
Banner printedBanner = printBanner(environment);
// 創建新的應用程序上下文
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
// 準備新的應用程序上下文
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
// 刷新新的應用程序上下文
refreshContext(context);
afterRefresh(context, applicationArguments);
// 應用啟動計時器結束計時
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 上下文已經刷新,應用程序已經啟動
listeners.started(context);
// 調用CommandLineRunner和ApplicationRunner
callRunners(context, applicationArguments);
} catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
} catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
2. 創建Spring Boot工程
需求:在頁面展示hello, world
2.1 手工創建
創建Maven工程
-
在pom.xml中配置parent和web的起步依賴
<?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.52lhp</groupId> <artifactId>hello</artifactId> <version>1.0-SNAPSHOT</version> <!--1. 繼承spring-boot-starter-parent Spring Boot版本控制的原理: spring-boot-starter-parent繼承了spring-boot-dependencies, 而spring-boot-dependencies中定義了各個依賴的版本 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> </parent> <!--2. 添加web的起步依賴--> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
-
創建啟動類
package com.lhp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HelloWorldApplication { public static void main(String[] args) { SpringApplication.run(HelloWorldApplication.class, args); } }
-
編寫業務代碼:
package com.lhp.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldController { @RequestMapping("/hello") public String hello() { return "hello, world"; } }
運行啟動類的main方法
2.2 通過Spring Initializr創建
在IDEA中創建工程時使用Spring Initializr
- 點擊Next轉到Spring Initializr Project Settings頁面-->配置Group、Artifact、Packaging、Java Version、Package等
- 點擊Next轉到Dependencies頁面-->選擇Spring Boot的版本和需要的依賴-->Next-->Finish
- 右鍵模塊-->Add Framework Support...-->選中Maven
2.3 部署Spring Boot項目
jar包部署:
在pom.xml中配置spring-boot-maven-plugin插件,將項目打成jar包
-
控制臺執行命令
java -jar xxx.jar
war包部署:
- 讓啟動類繼承SpringBootServletInitializer
- 在pom.xml中配置spring-boot-maven-plugin插件,將項目打成war包
- 在Web服務器(如:Tomcat)中部署war包
3. Spring Boot配置文件
Spring Boot的很多配置都有默認值,可以使用application.properties或application.yml(application.yaml)來修改默認配置。SpringBoot默認從Resource目錄加載自定義配置文件。
如果同時存在properties和yaml/yml,則properties優先級高于yaml/yml。
yaml/yml基本語法,參考:https://www.runoob.com/w3cnote/yaml-intro.html
- 大小寫敏感
- 使用縮進表示層級關系
- 縮進不允許使用tab,只允許空格
- 縮進的空格數不重要,只要相同層級的元素左對齊即可
-
#
表示注釋 - 值前面要加一個空格
- 對象鍵值對使用冒號結構表示key: value
- 以-開頭的行表示構成一個數組
- 純量包括:字符串、布爾值、整數、浮點數、Null、時間、日期
- &用來建立錨點,*用來引用錨點
3.1 獲取配置文件中的值
-
application.yml配置文件內容:
person: name: lhp age: 21 # 純量數據類型 sex: 男 # 數組數據類型 hobbies: - study - reading # 對象數據類型 pet: name: 狗 food: 骨頭 # 參數引用 age: ${person.age}
-
POJO:
@Data public class Pet implements Serializable { private String name; private String food; private Integer age; } // 1. 通過ConfigurationProperties把POJO的屬性和yml中key的值自動建立映射關系 // 2. 將POJO交給Spring容器管理(POJO需要有Setter方法) // 3. 使用時直接從Spring容器中獲取該POJO // 對象中的屬性若有自身,則可能映射失敗;如Person中含有Person @Data @Component @ConfigurationProperties(prefix = "person") public class Person implements Serializable { private String name; private Integer age; private String sex; private String[] hobbies; private Pet pet; }
-
獲取配置文件中的值:
import com.lhp.demo.pojo.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/test") public class TestController { // @Value("${屬性名}")只能獲取純量 @Value("${person.hobbies[0]}") private String personHobbies0; // 對象和數組的獲取方式相同 @Autowired private Person person; // 通過Environment可以獲取純量 @Autowired private Environment environment; @GetMapping("/scalars") private String scalars() { System.out.println(environment.getProperty("person.hobbies[0]")); return "person.hobbies[0]=" + personHobbies0; } @GetMapping("/object") private String object() { return "person=" + person; } }
3.2 使用指定的環境配置
-
方式1:編寫多個配置文件application-xxx
-
application.yml:
# 通過active指定要使用的配置文件 spring: profiles: # active的值為application-后面的部分 active: pro
-
application-dev.yml:
# 開發環境 server: port: 8081
-
application-pro.yml:
# 生產環境 server: port: 8082
-
application-test.yml:
# 測試環境 server: port: 8083
-
-
方式2:在application.yml中使用---來分割
spring: profiles: active: dev --- # 開發環境 server: port: 8081 spring: profiles: dev --- # 生產環境 server: port: 8082 spring: profiles: pro --- # 測試環境 server: port: 8083 spring: profiles: test
-
激活profiles的方式:
方式1:如上,在配置文件中配置spring.profiles.active=環境
-
方式2:運行時指定參數
java -jar xxx.jar --spring.profiles.active=test
-
方式3:配置jvm參數
-Dspring.profiles.active=dev
4. Spring Boot整合其他框架
4.1 整合MyBatis
-
添加依賴:
<!--mybatis的起步依賴--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <!--mysql驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
-
在application.yml中配置:
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/db01?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 username: root password: 123456 mybatis: # 配置mybatis映射文件的位置 mapper-locations: classpath:com/lhp/integration/dao/*Dao.xml
-
在啟動類上添加MapperScan注解,掃描Dao接口所在的包:
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // MapperScan會掃描指定包下的所有的接口,然后將接口的代理對象交給Spring容器 @MapperScan(basePackages = "com.lhp.integration.dao") public class IntegrationApplication { public static void main(String[] args) { SpringApplication.run(IntegrationApplication.class, args); } }
4.2 整合JUnit
-
添加依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
測試類所在的包最好在啟動類所在的包下
-
低版本Spring Boot使用:
package com.lhp.integration; import com.lhp.integration.dao.UserDao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class IntegrationApplicationTests { @Autowired private UserDao userDao; @Test public void contextLoads() { System.out.println(userDao.findAll()); } }
-
高版本Spring Boot使用:
package com.lhp.integration; import com.lhp.integration.dao.UserDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class IntegrationApplicationTests { @Autowired private UserDao userDao; @Test public void contextLoads() { System.out.println(userDao.findAll()); } }
4.3 整合Redis
-
添加依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
在application.yml中配置:
spring: redis: host: localhost port: 6379
-
在啟動類中配置Redis序列化機制:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @SpringBootApplication public class IntegrationApplication { public static void main(String[] args) { SpringApplication.run(IntegrationApplication.class, args); } // 配置Redis序列化機制 @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); // 設置Key的序列化機制為StringRedisSerializer template.setKeySerializer(new StringRedisSerializer()); // 設置value的序列化機制為JdkSerializationRedisSerializer template.setValueSerializer(new JdkSerializationRedisSerializer()); return template; } }
-
使用:
package com.lhp.integration; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; @SpringBootTest public class IntegrationApplicationTests { @Autowired private RedisTemplate redisTemplate; @Test public void redisTest() { redisTemplate.boundValueOps("name").set("lhp"); String name = String.valueOf(redisTemplate.boundValueOps("name").get()); System.out.println(name); } }
RedisTemplate支持的Redis序列化機制(RedisSerializer接口的實現類):
- GenericJackson2JsonRedisSerializer
- GenericToStringSerializer
- Jackson2JsonRedisSerializer
- JdkSerializationRedisSerializer(默認):要求key和value都實現Serializable接口
- OxmSerializer
- StringRedisSerializer
- 自己定義的RedisSerializer接口實現類
5. Spring Boot自動配置的原理
5.1 Condition接口
Condition接口和@Conditional注解是Spring4之后提供的,增加條件判斷功能,可以選擇性的注入Bean對象到Spring容器中。
自定義Condition實現類,需求:根據是否導入坐標,來選擇是否加載Bean
-
是否導入的坐標:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.2.0</version> </dependency>
-
POJO:
public class User { }
-
自定義Condition實現類:
package com.lhp.study.condition; import com.lhp.study.annotation.ConditionalOnClass; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.Map; public class OnClassCondition implements Condition { /** * @param context 上下文信息對象:可以獲取環境信息、容器工程、類加載器對象 * @param metadata 注解的元數據:可以獲取注解的屬性信息 * @return 是否匹配條件,true匹配,false不匹配 */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { /*try { Class.forName("redis.clients.jedis.Jedis"); // 如果加載成功,則依賴已經導入,返回true return true; } catch (ClassNotFoundException e) { e.printStackTrace(); // 如果加載失敗,則有依賴沒有導入,返回false return false; }*/ // 獲取注解的屬性信息 Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionalOnClass.class.getName()); // 獲取注解中name的值 String[] names = (String[]) annotationAttributes.get("name"); for (String name : names) { try { Class.forName(name); } catch (ClassNotFoundException e) { e.printStackTrace(); // 如果加載失敗,則有依賴沒有導入,返回false return false; } } // 如果指定的類都加載成功,則對應的依賴已經導入,返回true return true; } }
-
自定義一個注解:
package com.lhp.study.annotation; import com.lhp.study.condition.OnClassCondition; import org.springframework.context.annotation.Conditional; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional({OnClassCondition.class}) public @interface ConditionalOnClass { // 類全限定名的字符串數組 String[] name() default {}; }
-
配置類:
package com.lhp.study.config; import com.lhp.study.annotation.ConditionalOnClass; import com.lhp.study.condition.OnClassCondition; import com.lhp.study.pojo.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class UserConfig { @Bean // @Conditional注解表示一個組件只有在value指定的所有條件都匹配時才有資格注冊 // @Conditional(value = OnClassCondition.class) @ConditionalOnClass(name = "redis.clients.jedis.Jedis") public User user() { return new User(); } }
-
在啟動類中測試:
package com.lhp.study; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class StudyApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(StudyApplication.class, args); // 若導入坐標,則打印類信息;若沒有導入坐標,則拋出NoSuchBeanDefinitionException System.out.println(context.getBean("user")); } }
在org.springframework.boot.autoconfigure.condition包下有很多Spring已經定義好的Condition實現類和注解,如:
- ConditionalOnBean:當Spring容器中有某一個Bean時使用
- ConditionalOnClass:當目前類路徑下有某一個類時使用
- ConditionalOnMissingBean:當Spring容器中沒有某一個Bean時使用
- ConditionalOnMissingClass:當目前類路徑下沒有某一個類時使用
- ConditionalOnProperty:當配置文件中有某一個鍵值對時使用
5.2 切換內置的Web容器
org.springframework.boot.autoconfigure.web.embedded包下有4種Web容器定制器:
- JettyWebServerFactoryCustomizer
- NettyWebServerFactoryCustomizer
- TomcatWebServerFactoryCustomizer
- UndertowWebServerFactoryCustomizer
在spring-boot-starter-web中排除spring-boot-starter-tomcat依賴,然后添加其他的Web容器依賴即可:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!--在spring-boot-starter-web中排除spring-boot-starter-tomcat依賴-->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加其他的Web容器依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
5.3 加載第三方的Bean
@SpringBootApplication上有@SpringBootConfiguration,而@SpringBootConfiguration上有@Configuration,因此啟動類本身也是一個配置類,該配置類相當于Spring中的applicationContext.xml文件,用于加載配置使用。
@SpringBootApplication上有@EnableAutoConfiguration,這種@EnableXxx開頭的注解是Spring Boot中定義的一些動態啟用某些功能的注解,其底層原理實際上是用@import注解導入一些配置,來自動進行配置、加載Bean。
一路追蹤源碼:
@SpringBootApplication
@EnableAutoConfiguration
@Import({AutoConfigurationImportSelector.class})
String[] selectImports(AnnotationMetadata annotationMetadata)
AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata)
List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes)
META-INF/spring.factories
在spring-boot-autoconfigure-x.x.x.jar中的META-INF/spring.factories文件中就有各種自動配置類
@SpringBootApplication上有@ComponentScan,而@ComponentScan類似于xml中的包掃描context:component-scan;如果不指定掃描路徑,則掃描該注解修飾的啟動類所在的包及子包。
@Import注解用于導入其他的配置,讓Spring容器進行加載和初始化;其使用方式有:
- 直接導入Bean
- 導入配置類
- 導入ImportSelector的實現類
- 導入ImportBeanDefinitionRegistrar實現類
實現加載第三方的Bean示例:創建兩個工程enable1和enable2,enable2中有Bean,enable1依賴enable2,期望在enable1中直接使用enable2中的Bean
-
在enable2中創建POJO和配置類:
// POJO package com.lhp.enable2.pojo; public class User { } // 配置類 package com.lhp.enable2.config; import com.lhp.enable2.pojo.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class UserConfig { @Bean public User user() { return new User(); } }
在enable1中添加第三方依賴enable2的坐標
在enable1的啟動類中直接加載使用第三方依賴enable2中的Bean
-
解決NoSuchBeanDefinitionException:
方式1:在enable1的啟動類上使用@ComponentScan("com")注解將包掃描路徑放大
方式2:在enable1的啟動類上使用@Import({UserConfig.class})注解導入配置類
-
方式3:自定義一個注解@EnableUser,然后在enable1的啟動類上使用該注解
// 自定義注解 package com.lhp.enable2.config; import org.springframework.context.annotation.Import; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({UserConfig.class}) public @interface EnableUser { }
-
方式4:自定義一個ImportSelector實現類,然后在enable1的啟動類上使用@Import注解導入該實現類;此時不需要配置類
// ImportSelector實現類 package com.lhp.enable2.config; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.type.AnnotationMetadata; public class MyImportSelector implements ImportSelector { /** * @return 需要加載的Bean的全限定名數組 */ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { // 全限定名數組可以從配置文件中讀取 // 此時Bean的id為全限定名,可以通過getBean("com.lhp.enable2.pojo.User")或getBean(User.class)獲取 return new String[]{"com.lhp.enable2.pojo.User"}; } }
-
方式5:自定義一個ImportBeanDefinitionRegistrar實現類,然后在enable1的啟動類上使用@Import注解導入該實現類;此時不需要配置類
// ImportBeanDefinitionRegistrar實現類 package com.lhp.enable2.config; import com.lhp.enable2.pojo.User; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { String beanName = "user"; // 創建beanDefinition AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(User.class).getBeanDefinition(); // 注冊Bean registry.registerBeanDefinition(beanName, beanDefinition); } }
5.4 自定義starter起步依賴
需求:當加入jedis的坐標時,自動配置jedis的Bean,加載到Spring容器中
創建起步依賴工程starter,添加spring-boot-starter和jedis的坐標
-
創建配置的POJO:
package com.lhp.starter.pojo; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @Data @ConfigurationProperties(prefix = "redis") public class RedisProperties { // 給定默認值 private String host = "localhost"; private Integer port = 6379; }
-
創建自動配置類
// 自動配置類 package com.lhp.starter.autoconfigure; import com.lhp.starter.pojo.RedisProperties; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.Jedis; @Configuration // 啟用POJO,交給Spring容器管理,與配置文件建立映射關系 @EnableConfigurationProperties(RedisProperties.class) // 當類路徑下有Jedis這個類時再使用這個配置類 @ConditionalOnClass(Jedis.class) public class RedisAutoConfiguration { @Bean // 當沒有jedis這個Bean時再配置,避免和用戶自己的jedis沖突 @ConditionalOnMissingBean(name = "jedis") public Jedis jedis(RedisProperties redisProperties) { System.out.println(redisProperties); return new Jedis(redisProperties.getHost(), redisProperties.getPort()); } }
-
在resources下創建META-INF/spring.factories文件:
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.lhp.starter.autoconfigure.RedisAutoConfiguration
在其他工程中加入自定義的starter起步依賴的坐標,便可直接使用自定義starter起步依賴中的Bean
6. Spring Boot監控
6.1 Spring Boot Actuator
Spring Boot Actuator是Spring Boot自帶的組件,可以監控Spring Boot應用,如健康檢查、審計、統計、HTTP追蹤等
使用Spring Boot Actuator:
-
添加依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
-
在application.yml中配置:
management: # 配置健康端點開啟所有詳情信息 endpoint: health: show-details: always # 設置開放所有web相關的端點信息 endpoints: web: exposure: include: "*" # 設置info前綴的信息 info: name: lhp age: 21
部分監控路徑列表:
- /beans:描述應用程序上下文里全部的Bean及它們的關系
- /env:獲取全部環境屬性
- /env/{name}:根據名稱獲取特定的環境屬性值
- /health:報告應用程序的健康指標,這些值由HealthIndicator的實現類提供
- /info:獲取應用程序的定制信息,這些信息由info打頭的屬性提供
- /mappings:描述全部的URI路徑,以及它們和控制器(包含Actuator端點)的映射關系
- /metrics:報告各種應用程序度量信息,比如內存用量和HTTP請求計數
- /metrics/{name}:報告指定名稱的應用程序度量值
- /trace:提供基本的HTTP請求跟蹤信息(時間戳、HTTP頭等)
6.2 Spring Boot Admin
Spring Boot Admin是一個開源社區項目;它有兩個角色,Client和Server;應用程序作為Client向Server注冊;Server可以通過圖形化界面展示Client的監控信息
- 每一個Spring Boot工程都是一個Client
- Server可以收集統計所有相關Client注冊過來的信息,并進行匯總展示
使用Spring Boot Admin Server:
-
創建server工程,導入坐標:
<properties> <java.version>1.8</java.version> <spring-boot-admin.version>2.3.1</spring-boot-admin.version> </properties> <dependencies> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-dependencies</artifactId> <version>${spring-boot-admin.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
在啟動類上添加@EnableAdminServer注解來啟用Server功能
-
在application.yml中配置:
server: port: 8088
使用Spring Boot Admin Client:
-
創建server工程,導入坐標:
<properties> <java.version>1.8</java.version> <spring-boot-admin.version>2.3.1</spring-boot-admin.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-dependencies</artifactId> <version>${spring-boot-admin.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
-
在application.yml中配置:
spring: # 配置server的地址 boot: admin: client: url: http://localhost:8088 # 配置系統名稱 application: name: client management: endpoint: health: # 啟用健康檢查(默認就是true) enabled: true # 配置顯示所有的監控詳情 show-details: always endpoints: web: # 開放所有端點 exposure: include: "*"
瀏覽器訪問服務端地址:http://localhost:8088/