一、概述:
Spring Boot的强大之处就在于能够抽取场景作为启动器
只要加载了启动器 即可快速配置好相应的场景
那么 自定义starter(场景启动器)的步骤是:
1、首先要确定该场景需要的依赖是什么
2、然后编写自动配置
使用@Configuration
注解来指定一个类为配置类
使用@ConditionalOnXXX
注解 在指定条件成立的情况下该自动配置类才生效
例:
@ConditionalOnWebApplication(
type = Type.SERVLET
)
使用@AutoConfigurationAfter
注解来指定自动配置类的顺序
例:
@AutoConfigureAfter({
DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
使用@Bean
注解来给容器中添加组件
使用@ConfigurationProperties
注解结合相关的xxxProperties类来绑定相应的配置
例:
@ConfigurationProperties(
prefix = "spring.mvc"
)
使用@EnableConfigurationProperties
注解让xxxProperties类生效并加入到容器中
例:
@EnableConfigurationProperties({
WebMvcProperties.class, ResourceProperties.class})
还须在classpath下的META-INF
下的spring.factories文件中指定自动配置类的路径
让SpringBoot知道在启动时要加载的自动配置类有哪些
例:
# Initializers
org.springframework.context.ApplicationContextInitializer=\
net.zjitc.springboot.listener.HelloApplicationContextInitializer
# Listener
org.springframework.boot.SpringApplicationRunListener=\
net.zjitc.springboot.listener.HelloSpringApplicationRunListener
注意点:启动器应为一个空的jar文件 只提供辅助性的依赖管理 这些依赖可用于自动装配或其它类库
然后专门写一个自动配置模块 启动器是依赖于自动配置模块的
因此 只须引入启动器 即视为引入了自动配置模块
即:xxx-starter(启动器) → xxx-starter-autoconfigurer(自动配置模块)
命名规范:
- SpringBoot官方的命名空间:
前缀:“spring-boot-starter-”
模式:spring-boot-starter-模块名
例:spring-boot-starter-web - 自定义的命名空间:
后缀:“-spring-boot-starter”
模式:模块名-spring-boot-starter
例:mybatis-spring-boot-starter
二、项目创建
由于需要有启动器和自动配置模块这两样 因此为方便起见 在IDEA中 创建一个空的工程
点击加号 添加模块