在学习Spring Boot的过程中,接触最多的就是starter。使用者可以把starter当成是一种服务,使得使用某个功能时不需要关注各种依赖库的处理,不需要具体的配置信息,由Spring Boot自动通过classpath路径下的类发现需要的Bean,并织入bean。而自动装配就是Springboot最大的特性。
什么是定制starter
springBoot官方推出了很多的starter,那么在这些starter的背后,它的启动流程是什么?starter包含两大模块:
- autoconfigure 自动配置类
- starter 包含autoconfigure配置和其他的依赖
加入springBoot依赖
1
2
3
4
5
6
7
8
9
10
11
| <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
|
编写bean对象
1
2
3
4
5
| public class Hello {
public void say(String msg){
System.out.println(msg);
}
}
|
编写starter
1
2
3
4
5
6
7
| @Configuration
public class DemoAutoConfiguration {
@Bean
public Hello hello() {
return new Hello();
}
}
|
编写spring.factories
在 src/main/resources 目录下新建 META-INF 文件夹,然后新建 spring.factories 文件,这个文件用于告诉Spring Boot有那些自动配置类需要处理,因此它的内容是
1
2
| org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
xin.tianhui.cloud.starter.DemoAutoConfiguration
|
使用
在使用的项目中加入maven依赖,也就是咱们刚刚写好的starter
1
2
3
4
5
| <dependency>
<groupId>xin.tianhui.cloud</groupId>
<artifactId>demo-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
|
代码中注入starter初始化好的bean
1
2
3
4
5
6
7
8
| public class Application{
@Autowired
private Hello hello;
public void test(){
hello.say("hello");
}
}
|