简单手写一个Spring boot starter
一,背景
在Spring Boot项目中我们经常会用到各种starter,比如常用的spring-boot-starter, spring-cloud-starter,mybatis-spring-boot-starter, pagehelper-spring-boot-starter 等等, starter可以一次将所有需要的maven依赖引入进来,避免开发时少了依赖,特别是一些中间件,引入它的starter,基本上就可以不用再另外引入包了,比如:shardingsphere-jdbc-core-spring-boot-starter,redisson-spring-boot-starter,jasypt-spring-boot-starter,seata-spring-boot-starter等,减少了很多问题,给开发带来便利。
在日常开发中,我们可能也有需求去封装一些公用的全局的功能点,希望它引入简单,即插即用,如果日志脱敏,消息通知(比如企微或邮件通知)等,这个时候我们也可以封装一个starter,使用方引入这个starter就可以直接调用公用的方法或属性。
二,实现过程
我们以一个简单的给字符串加前缀的小功能点来说明实现starter和使用的过程
1,新建一个SpringBoot工程, 项目结构如下
2, 在pom.xml文件中引入依赖
<?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><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.5.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.xxx.custom</groupId><artifactId>new-custom-spring-boot-starter</artifactId><vers