SpringBoot里的Starter赋予了它易于使用的特性,使得我们可以很快的引入一个三方模块。例如RedisTemplate,我们只需要在Maven中增加spring-boot-starter-redis
即可。
Starter其实是一个可以通过Maven或者Greadle引入module,在module内部把需要的bean注入到主工程的Spring ApplicationContext中。
当然,通常我们会获取一些主工程里面的配置文件,如
spring.redis.host=
spring.redis.port=
......
首先
要在Starter
工程中添加依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
这两个依赖主要是负责自动加载配置文件。
第二步
我们要添加自动加载配置文件的ConfigurationProperties
,通过一个注解来声明。
@Data //通过lombok插件简化get/set代码
@ConfigurationProperties("spring.redis")
public class RedisProperties {
private Integer database;
private String host;
private Integer port;
private String password = ""; // 也可以通过"="赋值来使用默认值
}
// 注意,如果不使用@Data注解,必须手动生成 Get/Set方法,否则配置文件中的值无法加载到Properties中,同时也会报错。
第三步
也是最重要的一步,配置AutoConfigure
。
@Configuration
@ConditionalOnClass(RedisProperties.class)
@EnableConfigurationProperties(RedisProperties.class)
public class ScheduleAutoConfigure {
}
@ConditionalOnClass
作用是,如果括号中的类在类路径(classpath才会实例化一个Bean)。
@EnableConfigurationProperties
作用是,使括号内的Properties
生效。
最后
AutoConfigure中使用@Bean把类注入到IoC容器中。
@Bean
@ConditionalOnMissingBean
public Schedule schedule() {
return new Schedule(Executors.newCachedThreadPool(), jedisPool);
}
@ConditionalOnMissingBean
作用是,当容器中不存在该Bean使,就创建一个Bean。
使用方法很简单,在一个SpringBoot项目中,当做普通的依赖引入即可。
引入时,注意要使用Starter项目的pom.xml
中定义的groupId
、artifactId
、version
。
尾巴
我这里有一个简单的例子,是Redis任务调度模块Starter:https://github.com/wellCh4n/Redis-Schedule-Spring-Boot-Starter
标题:SpringBoot Starter 不完全使用指南
作者:wellCh4n
地址:http://www.wellch4n.com/articles/2019/09/06/1567773452920.html