有時候,springboot官方提供的場景啟動器(starter)並不能很好的滿足我們的需求。
一些配置類仍然需要我們自行編寫(例如mybatis plus的分頁插件配置),在多模塊項目中,這種模式代碼可能多個模塊都需要編寫一次,這時候,我們可以考慮自行編寫場景啟動器,然后在common模塊引入即可。
命名規約
spring官方:
spring-boot-starter-xxx
自定義:
xxx-spring--boot-starter
自定義starter步驟
創建一個普通的空工程
創建一個普通maven項目
這里我將工程命名為gulimall-spring-boot-starter
創建自動配置模塊
選擇springboot工程構建工具:
模塊命名為gulimall-spring-boot-autoconfigure。
這里可以啥都不選,后面可以自行修改
修改pom文件
starter引入autoconfigure模塊

autoconfigure模塊,先刪除build,然后刪除spring-boot-test,再刪除test包,因為用不到,我這里引入mybatis-plus的starter。
編寫配置類
先刪除主啟動類,然后新建一個配置類
/**
* mybatis plus分頁插件配置
* @author wj
*/
@ConditionalOnClass(value = {PaginationInterceptor.class})
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
配置進META-INF\spring.factories:
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.wj.gulimall.autoconfigure.config.MybatisPlusConfig

這樣,項目在啟動的時候,會見該自動配置類進行掃描。
打包到本地倉庫
先打包autoconfigure模塊:
雙擊install
構建成功后,再同樣步驟,構建starter模塊
自定義場景啟動的測試
構建成功后,我們就可以再其他項目中的公用模塊引入自定義starter:

而我寫的分頁插件配置仍然生效。
后台日志也打印出分頁查詢的sql

我這里日志打印使用了p6spy,當然p6spy的全局配置也可以寫入自定義的starter中(這里不再贅述)
我們也可以在不要配置數據源的模塊中,直接排除mybatis-plus的依賴也不會報錯,因為我們在配置類上加上了@ConditionalOnClass(value = {PaginationInterceptor.class}),只有當PaginationInterceptor.class在類路徑上存在,才實例化當前Bean。
