当需要把一些共用的 api 封装成 jar 包的时候,就可以尝试自定义启动 器来做。
自定义启动器用到的就是 springboot 中的 SPI 原理,springboot 会去加载 meta-INF/spring.factories 配置文件。加载 EnableAutoConfiguration 为 key 的所有类。
利用这一点,我们也可以定义一个工程也会有这个文件。
1、定义启动器核心工程 工程结构custom-spring-boot-starter-autoconfigurer
─src
└─main
├─java
│ └─len
│ └─hgy
│ │ CustomSpringBootStarterAutoconfigurerApplication.java
│ │
│ └─start
│ CustomStarterRun.java
│ JackTemplate.java
│ RedisConfig.java
│
└─resources
│ application.properties
│
└─meta-INF
spring.factories
spring.factories 配置内容
org.springframework.boot.autoconfigure.EnableAutoConfiguration= len.hgy.start.CustomStarterRun被 springboot SPI 加载的类
@Configuration
@ConditionalOnClass(MyTemplate.class)
@EnableConfigurationProperties(RedisConfig.class)
public class CustomStarterRun {
@Autowired
private RedisConfig redisConfig;
@Bean
public MyTemplate jackTemplate() {
return new MyTemplate(redisConfig);
}
}
这个 MyTemplate 实例就是我们封装的通用 API,其他工程可以直接导入 jar 使用的。
2、自定义 starter我们还会定义一个没代码的工程,在这个工程里面没有任何代码,只有一个 pom 文件。Pom 里面就是对前面核心工程 jar 包的导入
工程结构:
springboot-starter-mytemplate │ pom.xml
pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE len.hgy spring-boot-starter-template 1.0-SNAPSHOT jackTemplate-spring-boot-starter http://www.example.com UTF-8 1.8 1.8 len.hgy custom-spring-boot-starter-autoconfigurer 0.0.1-SNAPSHOT
主类
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
打包
mvn clean package -Dmaven.test.skip=true
运行
java -jar spring-boot-starter-template-1.0-SNAPSHOT.jar



