SpringBoot自定义Starter
SpringBoot提供了很多封装好的Starter供我们使用,如果我们有成熟的功能也可以封装成starter供别人使用。
假设有一个成熟的功能:定时往控制台打印信息,想把他封装成一个Starter,看看如何封装。 创建空白SpringBoot项目
创建一个新的SpringBoot项目:my-spring-boot-starter,在这个项目里实现主体业务功能。
创建属性类
创建属性类MyMessageProperties,这里定义了字段msgstr,表示将来要往控制台输出的消息。
这是设置了默认值,也通过@ConfigurationProperties注解设置从配置文件application.yml中读取用户配置。用户配置有更高的优先级。 @ConfigurationProperties(value = "mymsg") public class MyMessageProperties { /** * 控制台输出的消息 */ private String msgstr = "这是默认输出的信息"; public String getMsgstr() { return msgstr; } public void setMsgstr(String msgstr) { this.msgstr = msgstr; } }创建自动配置类
使用@EnableConfigurationProperties注解加载上一步的属性类。
创建定时任务,每隔1秒中在控制打印从MyMessageProperties中读取的配置信息。 @EnableConfigurationProperties(MyMessageProperties.class) @EnableScheduling public class MyMessageAutoConfiguration { @Autowired private MyMessageProperties myMessageProperties; @Scheduled(fixedDelay = 1000) public void printMsg(){ System.out.println(this.myMessageProperties.getMsgstr()); } } 加载自动配置类
创建文件:src/main/resources/META-INF/spring.factories
在文件中配置启动时加载的配置类名。
配置后,在SpringBoot启动时,就会自动加载指定的配置类。 org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.example.myspringbootstarter.config.MyMessageAutoConfiguration配置自动提示
在配置文件中输入配置项时,会有相关提示。
通过引入spring-boot-configuration-processor实现此功能。 org.springframework.boot spring-boot-configuration-processor
执行Maven install命令,将文件target/classes/META-INF/spring-configuration-metadata.json复制到src/main/resources/spring-configuration-metadata.json
完成后将spring-boot-configuration-processor从pom文件中删掉,不然会出现2组相同的提示信息。 打包
将开发完成的starter项目打包。
执行Maven的install命令。
使用
在其他项目中引入自定义的starer com.example my-spring-boot-starter 0.0.1-SNAPSHOT
在项目application.properties中配置要打印的字符串,配置时会给出提示信息。
配置打印的信息 mymsg.msgstr=hello
运行项目,会在控制台打印在配置文件中配置的信息。
如果删除application.properties中的配置,则会打印默认信息。
至此,我们自定义的Starter已经可以正常使用了。