一、简介
SpringBoot 最强大的功能就是把我们常用的场景抽取成了一个个starter(场景启动器),我们通过引入SpringBoot 为我提供的这些场景启动器,我们再进行少量的配置就能使用相应的功能。即使是这样,SpringBoot也不能囊括我们所有的使用场景,往往我们需要自定义starter,来简化我们对SpringBoot的使用。
下面话不多说了,来一起看看详细的介绍吧
二、如何自定义starter
1.实例
如何编写自动配置 ?
我们参照@WebMvcAutoConfiguration为例,我们看看需要准备哪些东西,下面是WebMvcAutoConfiguration的部分代码:
@Configuration@ConditionalOnWebApplication@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class})@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})@AutoConfigureOrder(-2147483638)@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})public class WebMvcAutoConfiguration { @Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class}) @EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class}) public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter { @Bean @ConditionalOnBean({View.class}) @ConditionalOnMissingBean public BeanNameViewResolver beanNameViewResolver() { BeanNameViewResolver resolver = new BeanNameViewResolver(); resolver.setOrder(2147483637); return resolver; } }}
我们可以抽取到我们自定义starter时,同样需要的一些配置。
@Configuration //指定这个类是一个配置类@ConditionalOnXXX //指定条件成立的情况下自动配置类生效@AutoConfigureOrder //指定自动配置类的顺序@Bean //向容器中添加组件@ConfigurationProperties //结合相关xxxProperties来绑定相关的配置@EnableConfigurationProperties //让xxxProperties生效加入到容器中自动配置类要能加载需要将自动配置类,配置在META-INF/spring.factories中org.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
模式
我们参照 spring-boot-starter 我们发现其中没有代码:
我们在看它的pom中的依赖中有个 springboot-starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId></dependency>
我们再看看 spring-boot-starter 有个 spring-boot-autoconfigure
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId></dependency>
关于web的一些自动配置都写在了这里 ,所以我们有以下总结:
启动器starter只是用来做依赖管理
需要专门写一个类似spring-boot-autoconfigure的配置模块
用的时候只需要引入启动器starter,就可以使用自动配置了
命名规范
官方命名空间
- 前缀:spring-boot-starter-
- 模式:spring-boot-starter-模块名
- 举例:spring-boot-starter-web、spring-boot-starter-jdbc
自定义命名空间
- 后缀:-spring-boot-starter
- 模式:模块-spring-boot-starter
- 举例:mybatis-spring-boot-starter
三、自定义starter实例
我们需要先创建两个工程 hello-spring-boot-starter 和 hello-spring-boot-starter-autoconfigurer
1. hello-spring-boot-starter
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:///gf-huanchupk/SpringBootLearning
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。