介绍

SpringBoot在配置上相比Spring要简单许多, 其核心在于spring-boot-starter。
在使用SpringBoot来搭建一个项目时, 只需要引入官方提供的starter, 就可以直接使用, 免去了各种配置。
starter简单来讲就是引入了一些相关依赖和一些初始化的配置。

SpringBoot官方提供了很多starter,第三方也可以定义starter。为了加以区分,starter从名称上进行了如下规范:

  • SpringBoot官方提供的starter名称为:spring-boot-starter-xxx

    例如Spring官方提供的spring-boot-starter-web

  • 第三方提供的starter名称为:xxx-spring-boot-starter

    例如由mybatis提供的mybatis-spring-boot-starter

自定义starter

开发starter

1.创建starter工程hello-spring-boot-starter并配置pom.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
       <artifactId>hello-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>

......略

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>

2.创建配置属性类

1
2
3
4
5
@Data
@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
private String name;
}

3.创建服务类

1
2
3
4
5
6
7
8
9
10
11
public class HelloService {
private String name;

public HelloService(String name) {
this.name = name;
}

public String sayHello(){
return "hello " + name + "!";
}
}

4.创建自动配置类HelloServiceAutoConfiguration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
private HelloProperties helloProperties;

public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}

@Bean
@ConditionalOnMissingBean
public HelloService helloService(){
return new HelloService(helloProperties.getName());
}
}

5.在resources目录下创建META-INF/spring.factories

1
2
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
site.milanchen.config.HelloServiceAutoConfiguration

至此starter已经开发完成了,可以将当前starter安装到本地maven仓库供其他应用来使用。

使用starter

1.配置pom.xml文件

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--导入自定义starter-->
<dependency>
<groupId>cn.pf</groupId>
<artifactId>hello-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>

2.创建application.yml文件

1
2
3
4
server:
port: 8080
hello:
name: world

3.创建HelloController

1
2
3
4
5
6
7
8
9
10
11
12
@RestController
@RequestMapping("/hello")
public class HelloController {
// HelloService在我们自定义的starter中已经完成了自动配置,所以此处可以直接注入
@Autowired
private HelloService helloService;

@GetMapping("/say")
public String sayHello(){
return helloService.sayHello();
}
}