手撸springboot starter启动器

手撸springboot starter启动器

前言:starter启动器是springboot能够自动配置快速运行起来的核心,springboot启动器除了帮助我们引入一些必要的jar包以外还有一个AutoConfiguration自动配置类,springboot项目在启动时扫描所有spring.factories文件自动加载里面的配置类信息,实例化其中的bean,并加入spring的IOC容器,在了解了启动器加载原理下面我们来手写一个简单的启动器(其实特别简单).

1.idea中新建一个普通的maven项目,作为starter启动器项目

2.在pom文件中添加如下jar包坐标:

手撸springboot starter启动器

3.创建如下结构以及相关类

手撸springboot starter启动器
FormatTemplate类:
手撸springboot starter启动器
User类:
手撸springboot starter启动器
FormatAutoConfiguration类:
手撸springboot starter启动器
@EnableConfigurationProperties(FormatProperties.class)表示允许自动配置类

FormatProperties类:
@ConfigurationProperties(prefix = “test”)
手撸springboot starter启动器
@ConfigurationProperties(prefix = “test”)表示当前是一个属性配置类,prefix = "test"表示以前缀为test来配置此属性

4.在resources文件夹下新建META-INF,创建spring.factories文件,文件内容是key-value形式,key为springboot中允许自动配置类全限定类名,value为本项目自动配置类的限定类名

手撸springboot starter启动器
手撸springboot starter启动器
链接: link.

5.打包发布,待其他项目引入

手撸springboot starter启动器
打包之后:
手撸springboot starter启动器手撸springboot starter启动器
其他项目引入依赖:
手撸springboot starter启动器
application.properties中配置属性:
手撸springboot starter启动器
调用方法:
手撸springboot starter启动器