SpringBoot自定义starter
2020.04.25 09:23
2020.04.25 09:23
1. 前言
SpringBoot之所以如此方便,就是其为我们提供了很多的starter,无论是否是官方的starter;
那么如何自定义一个starter?其实很简单,需要说的是,自定义starter,就还得理解SpringBoot的自动配置
SpringBoot的自动配置类,会自动读取类路径下的spring.factories
文件,该文件位于:META-INF
目录下;
2. 步骤
2.1. 新建普通的maven工程
并导入autoconfigure包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
lombok是我个人导入的,你也可以不导入;
2.2. 新建HelloProperties
该类主要是读取配置文件的值:
@ConfigurationProperties(prefix = "kuan")
@Data
@Component
public class HelloProperties {
private String name;
private String pass;
}
前缀是kuan
与此对应,我们需要在application.yml
写出这两个变量的值,这里的变量也即默认值;
kuan:
name: 无道
pass: 1234
2.3. 新建helloService
顾名思义,这里就是我们自己的starter要做的业务逻辑,这里很简单,我们就打印一句话即可:
@Data
public class HelloService {
private String name;
private String pass;
public void sayHello() {
System.out.println(name + ",say to Hello, and my pass is " + pass);
}
}
2.4. 新建自动配置类
@Configuration
@EnableConfigurationProperties(HelloProperties.class)
@ConditionalOnClass(HelloService.class)
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setName(helloProperties.getName());
helloService.setPass(helloProperties.getPass());
return helloService;
}
}
也即是说:当存在HelloService
这个类时,该配置类生效(并初始化一个实例,加入到spring容器)
2.5. META-INF\spring.factories
新建META-INF\spring.factories
文件,内容是:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.misiai.config.HelloServiceAutoConfiguration
必须要加入这段话,spring才能识别我们的自动配置类;
所有文件结构:
2.6. 安装到本地仓库
你可以使用命令行mvn install
或者直接在idea的maven中安装,如下:
3. 测试
然后我们就可以新建一个SpringBoot项目,来测试我们自定义的starter了:
在pom依赖中,加入我们的starter:
<dependency>
<groupId>com.misiai</groupId>
<artifactId>my-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
测试:
@SpringBootTest
class TestApplicationTests {
@Autowired
HelloService helloService;
@Test
void contextLoads() {
helloService.sayHello();
}
}
没有问题:
本节阅读完毕!
(分享)