作者:
尹吉?dú)g
微信公眾號(hào):猿天地
Spring Boot的方便體現(xiàn)在簡化了很多繁瑣的配置滓窍,對(duì)開發(fā)人員來說是一個(gè)福音旅急,通過引入各種Spring Boot Starter包可以快速的搭建出一個(gè)項(xiàng)目的腳手架。
目前提供的Spring Boot Starter包有:
spring-boot-starter-web:快速構(gòu)建基于Spring MVC的Web項(xiàng)目捐祠,使用Tomcat做默認(rèn)嵌入式容器啰挪。
spring-boot-starter-data-redis:操作Redis。
spring-boot-starter-data-mongodb:操作Mongodb屈溉。
spring-boot-starter-data-jpa:操作Mysql。
spring-boot-starter-activemq:操作Activemq抬探。
等等......
自動(dòng)配置非常方便子巾,當(dāng)我們要操作Mongodb的時(shí)候,只需要引入spring-boot-starter-data-mongodb的依賴小压,然后配置Mongodb的鏈接信息 spring.data.mongodb.uri=mongodb://localhost/test
就可以使用MongoTemplate來操作數(shù)據(jù)线梗,MongoTemplate的初始化工作全部交給Starter來完成。
自動(dòng)配置麻煩的是當(dāng)出現(xiàn)錯(cuò)誤時(shí)场航,排查問題的難度上升了缠导。自動(dòng)配置的邏輯都在Spring Boot Starter中廉羔,要快速的能夠定位問題溉痢,那么你必須得了解Spring Boot Starter的內(nèi)部原理。接下來我們自己動(dòng)手來實(shí)現(xiàn)一個(gè)Spring Boot Starter憋他。
開發(fā)Starter步驟:
創(chuàng)建Starter項(xiàng)目
定義Starter需要的配置(Properties)類
編寫自動(dòng)配置類
編寫spring.factories文件加載自動(dòng)配置類
編寫配置提示文件spring-configuration-metadata.json(不是必須的)
創(chuàng)建一個(gè)項(xiàng)目spring-boot-starter-demo孩饼,Pom.xml配置如下:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
創(chuàng)建一個(gè)配置類,用于在屬性文件中配置值竹挡,相當(dāng)于spring.data.mongo這種形式
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
@Data
@ConfigurationProperties("spring.user")
public class UserPorperties {
private String name;
}
@ConfigurationProperties指定了配置的前綴镀娶,也就是spring.user.name=XXX
再定義一個(gè)Client,相當(dāng)于MongoTemplate揪罕,里面定一個(gè)方法梯码,用于獲取配置中的值
public class UserClient {
private UserPorperties userPorperties;
public UserClient() {
}
public UserClient(UserPorperties p) {
this.userPorperties = p;
}
public String getName() {
return userPorperties.getName();
}
}
一個(gè)最基本的Starter包定義好了,但目前肯定是不能使用UserClient 好啰,因?yàn)槲覀儧]有去自動(dòng)構(gòu)建UserClient 的實(shí)例轩娶,接下來開始構(gòu)建UserClient
@Configuration
@EnableConfigurationProperties(UserPorperties.class)
public class UserAutoConfigure {
@Bean
@ConditionalOnProperty(prefix = "spring.user",value = "enabled",havingValue = "true")
public UserClient userClient(UserPorperties userPorperties) {
return new UserClient(userPorperties);
}
}
Spring Boot會(huì)默認(rèn)掃描跟啟動(dòng)類平級(jí)的包,如果我們的Starter跟啟動(dòng)類不在同一個(gè)主包下框往,如何讓UserAutoConfigure 生效鳄抒?
第一種方式:
在resources下創(chuàng)建一個(gè)META-INF文件夾,然后在META-INF文件夾中創(chuàng)建一個(gè)spring.factories文件椰弊,文件中指定自動(dòng)配置的類
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.cxytiandi.demo.UserAutoConfigure
Spring Boot啟動(dòng)時(shí)會(huì)去讀取spring.factories文件许溅,然后根據(jù)配置激活對(duì)應(yīng)的配置類,到底為止就簡單的實(shí)現(xiàn)了一個(gè)Starter包秉版。
現(xiàn)在可以在其他的項(xiàng)目中引入這個(gè)Starter包:
<dependency>
<groupId>com.example</groupId>
<artifactId>spring-boot-starter-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
引入之后就直接可以使用UserClient贤重,UserClient 在項(xiàng)目啟動(dòng)的時(shí)候已經(jīng)自動(dòng)初始化好。
@RestController
public class UserController {
@Autowired
private UserClient userClient;
@GetMapping("/user/name")
public String getUserName() {
return userClient.getName();
}
}
很多時(shí)候我們不想引入了Starter包就執(zhí)行初始化的邏輯清焕,想要用戶來指定是否要開啟Starter包的自動(dòng)配置功能游桩,比如常用的@EnableAsync這個(gè)注解就是用于開啟調(diào)用方法異步執(zhí)行的功能牲迫。
同樣的我們也可以通過注解的方式來開啟是否自動(dòng)配置,如果用注解的方式借卧,那么spring.factories就不需要編寫了盹憎,下面來看怎么定義啟用自動(dòng)配置的注解。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({UserAutoConfigure.class})
public @interface EnableUserClient {
}
核心是@Import({UserAutoConfigure.class})這行代碼铐刘,通過導(dǎo)入的方式實(shí)現(xiàn)把UserAutoConfigure實(shí)例加入SpringIOC容器中陪每,這樣就能開啟自動(dòng)配置了。
使用方式就是在啟動(dòng)類上加上該注解镰吵,代碼入下:
@EnableUserClient
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
在某些場(chǎng)景下檩禾,UserAutoConfigure中會(huì)配置多個(gè)對(duì)象,對(duì)于這些對(duì)象疤祭,不想全部配置盼产,也想讓用戶指定需要開啟配置的時(shí)候再去構(gòu)建對(duì)象,這個(gè)時(shí)候我們可以通過@ConditionalOnProperty來指定是否開啟配置的功能勺馆,代碼如下:
@Bean
@ConditionalOnProperty(prefix = "spring.user",value = "enabled",havingValue = "true")
public UserClient userClient(UserPorperties userPorperties) {
return new UserClient(userPorperties);
}
通過上面的配置戏售,只有當(dāng)啟動(dòng)類加了@EnableUserClient并且配置文件中spring.user.enabled=true的時(shí)候才會(huì)自動(dòng)配置UserClient 。
在自定義Starter包的過程中草穆,還有一點(diǎn)也比較重要灌灾,就是需要對(duì)配置的內(nèi)容項(xiàng)進(jìn)行提示,需要注意的是Eclipse中是不支持提示的悲柱,我用的Spring Tools 4 for Eclipse锋喜,如下圖:
定義提示內(nèi)容需要在META-INF中創(chuàng)建一個(gè)spring-configuration-metadata.json
{
"properties": [
{
"name": "spring.user.name",
"defaultValue": "cxytinadi"
},
{
"name": "spring.user.enabled",
"type": "java.lang.Boolean",
"defaultValue": false
}
]
}
name:配置名
type:配置的數(shù)據(jù)類型
defaultValue:默認(rèn)值