1、自定义starter的步骤
- 这个场景需要使用的依赖是什么
- 如何编写自动配置
2、自动配置需要使用到的一些注解
@Configuration //指定这个类是一个配置类
@ConditionalOnXXX //在指定条件成立的情况下自动配置类生效
@AutoConfigureAfter //指定自动配置类的顺序
@Bean //给容器中添加组件
@ConfigurationPropertie结合相关xxxProperties类来绑定相关的配置
@EnableConfigurationProperties //让xxxProperties生效加入到容器中
自动配置类要能加载 将需要启动就加载的自动配置类,配置在META‐INF/spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
3、starter的组织模式
启动器只用来做依赖管理
需要专门写一个自动配置模块
启动器依赖自动配置;别人只需要引入启动器即可
【注意】
Spring官方的启动器:spring-boot-starter-xxx
自定义启动器名称一般为: xxx-spring-boot-starter
4、如何创建一个starter
1)新建一个启动器的maven项目,里面引入你想引入的依赖
2)新建一个启动器的自动配置项目
a、pom文件中引入
<!--所有启动器的基本配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
b、src文件件夹中添加自动配置
//1、新建一个HelloService
public class HelloService {
HelloProperties properties;
public HelloProperties getProperties() {
return properties;
}
public void setProperties(HelloProperties properties) {
this.properties = properties;
}
public String sayHello(String name) {
return properties.getPrefix() + name + "" + properties.getSuffix();
}
}
//2、新建一个HelloProperties,用于和配置文件中的配置绑定
@ConfigurationProperties(prefix = "atguigu.hello")
public class HelloProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
//3、编写自动配置,将HelloService被自动发现并被注入到容器中
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(HelloProperties.class) //将HelloProperties这个类注入到容器中
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setProperties(helloProperties);
return helloService;
}
}
3)spring.factories中配置需要加载的自动配置类
要想b)的配置java配置生效,需要在 resource-> META-INF -> spring.factories 下指定SpringBoot启动过程中,需要加载的自动配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.atguigu.starter.HelloServiceAutoConfiguration
4)打包
在启动器的pom文件中引入启动器自动配置类的坐标,并将两个工程都install进maven仓库
5)测试
新建一个工程引入启动器。注入helloService
application.properties中配置
atguigu.hello.prefix = hello
atguigu.hello.suffix = goodmarning
请求 http://localhost:8080/hello?name=houchen