# SpringBoot学习笔记(四)-自定义一个Starter
[TOC]
SpringBoot是由众多的Starter组成的,可以将其理解为一个可插拔式的插件,正是由于这些Starter的存在,使得我们只需要使用Starter,无需关注各种依赖库的处理,例如我们需要使用Redis插件,可以直接在pom.xml文件中引用官方的`spring-boot-starter-redis`,使用MongoDB,可以引用`spring-boot-starter-data-mongodb`
**为什么要自定义一个Starter?**
开发过程中,经常会有一些独立于业务之外的配置模块,我们将这些可以独立于业务代码的功能封装成一个个starter,其他模块只需要引用该依赖即可,SpringBoot会对其进行自动装配
**自定义starter的命名规则**
SpringBoot提供的starter以`spring-boot-starter-xxx`的方式命名,官方建议自定义的starter使用`xxx-spring-boot-starter`命名规则,用于区分是官方提供还是自定义的starter
## 自定义starter
创建Maven工程,并导入SpringBoot的自动装配依赖
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
</dependencies>
```
编写JavaBean与配置类
```java
@EnableConfigurationProperties(SimpleBean.class)
@ConfigurationProperties(prefix = "simplebean")
public class SimpleBean {
private int id;
private String name;
}
```
```java
@Configuration
@ConditionalOnClass
public class MyAutoConfiguration {
static {
System.out.println("MyAutoConfiguration init....");
}
@Bean
public SimpleBean simpleBean() {
return new SimpleBean();
}
}
```
resources下创建相应的/META-INF/spring.factories文件并写入配置
```properties
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.lagou.config.MyAutoConfiguration
```

这样一个自定义的starter就定义好了
## 使用自定义的starter
在需要使用这个自定义的starter的模块pom.xml文件中引用此依赖
```xml
<dependency>
<groupId>com.lagou</groupId>
<artifactId>zdy-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
```
在模块的全局配置文件中进行注入配置信息测试是否可用
```properties
simplebean.id=1
simplebean.name=自定义starter
```
```java
//测试自定义starter
@Autowired
private SimpleBean simpleBean;
@Test
public void zdyStarterTest(){
System.out.println(simpleBean);
}
```
SpringBoot学习笔记(四)-自定义一个Starter