一、简介

SpringBoot 最强大的功能就是把我们常用的场景抽取成了一个个starter(场景启动器),我们通过引入springboot 为我提供的这些场景启动器,我们再进行少量的配置就能使用相应的功能。即使是这样,springboot也不能囊括我们所有的使用场景,往往我们需要自定义starter,来简化我们对springboot的使用。

二、如何自定义starter

1.实例

如何编写自动配置 ?

我们参照@WebMvcAutoConfiguration为例,我们看看们需要准备哪些东西,下面是WebMvcAutoConfiguration的部分代码:

  1. @Configuration
  2. @ConditionalOnWebApplication
  3. @ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class})
  4. @ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
  5. @AutoConfigureOrder(-2147483638)
  6. @AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
  7. public class WebMvcAutoConfiguration {
  8. @Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
  9. @EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class})
  10. public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {
  11. @Bean
  12. @ConditionalOnBean({View.class})
  13. @ConditionalOnMissingBean
  14. public BeanNameViewResolver beanNameViewResolver() {
  15. BeanNameViewResolver resolver = new BeanNameViewResolver();
  16. resolver.setOrder(2147483637);
  17. return resolver;
  18. }
  19. }
  20. }

我们可以抽取到我们自定义starter时同样需要的一些配置。

  1. @Configuration //指定这个类是一个配置类
  2. @ConditionalOnXXX //指定条件成立的情况下自动配置类生效
  3. @AutoConfigureOrder //指定自动配置类的顺序
  4. @Bean //向容器中添加组件
  5. @ConfigurationProperties //结合相关xxxProperties来绑定相关的配置
  6. @EnableConfigurationProperties //让xxxProperties生效加入到容器中
  7. 自动配置类要能加载需要将自动配置类,配置在META-INF/spring.factories
  8. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  9. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
  10. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\

模式

我们参照 spring-boot-starter 我们发现其中没有代码:

我们在看它的pom中的依赖中有个 springboot-starter

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter</artifactId>
  4. </dependency>

我们再看看 spring-boot-starter 有个 spring-boot-autoconfigure

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-autoconfigure</artifactId>
  4. </dependency>

关于web的一些自动配置都写在了这里 ,所以我们有总结:

  1. 启动器starter只是用来做依赖管理
  2. 需要专门写一个类似spring-boot-autoconfigure的配置模块
  3. 用的时候只需要引入启动器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-starterhello-spring-boot-starter-autoconfigurer

1. hello-spring-boot-starter

1.pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.gf</groupId>
  6. <artifactId>hello-spring-boot-starter</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>hello-spring-boot-starter</name>
  10. <!-- 启动器 -->
  11. <dependencies>
  12. <!-- 引入自动配置模块 -->
  13. <dependency>
  14. <groupId>com.gf</groupId>
  15. <artifactId>hello-spring-boot-starter-autoconfigurer</artifactId>
  16. <version>0.0.1-SNAPSHOT</version>
  17. </dependency>
  18. </dependencies>
  19. </project>

同时删除 启动类、resources下的文件,test文件。

2. hello-spring-boot-starter-autoconfigurer

1. pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.gf</groupId>
  6. <artifactId>hello-spring-boot-starter-autoconfigurer</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>hello-spring-boot-starter-autoconfigurer</name>
  10. <description>Demo project for Spring Boot</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>1.5.9.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <!-- 引入spring-boot-starter,所有starter的基本配合 -->
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter</artifactId>
  27. </dependency>
  28. </dependencies>
  29. </project>

2. HelloProperties

  1. package com.gf.service;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. @ConfigurationProperties(prefix = "gf.hello")
  4. public class HelloProperties {
  5. private String prefix;
  6. private String suffix;
  7. public String getPrefix() {
  8. return prefix;
  9. }
  10. public void setPrefix(String prefix) {
  11. this.prefix = prefix;
  12. }
  13. public String getSuffix() {
  14. return suffix;
  15. }
  16. public void setSuffix(String suffix) {
  17. this.suffix = suffix;
  18. }
  19. }

3. HelloService

  1. package com.gf.service;
  2. public class HelloService {
  3. HelloProperties helloProperties;
  4. public HelloProperties getHelloProperties() {
  5. return helloProperties;
  6. }
  7. public void setHelloProperties(HelloProperties helloProperties) {
  8. this.helloProperties = helloProperties;
  9. }
  10. public String sayHello(String name ) {
  11. return helloProperties.getPrefix()+ "-" + name + helloProperties.getSuffix();
  12. }
  13. }

4. HelloServiceAutoConfiguration

  1. package com.gf.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
  4. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. @Configuration
  8. @ConditionalOnWebApplication //web应该生效
  9. @EnableConfigurationProperties(HelloProperties.class)
  10. public class HelloServiceAutoConfiguration {
  11. @Autowired
  12. HelloProperties helloProperties;
  13. @Bean
  14. public HelloService helloService() {
  15. HelloService service = new HelloService();
  16. service.setHelloProperties( helloProperties );
  17. return service;
  18. }
  19. }

5. spring.factories

resources 下创建文件夹 META-INF 并在 META-INF 下创建文件 spring.factories ,内容如下:

  1. # Auto Configure
  2. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  3. com.gf.service.HelloServiceAutoConfiguration

到这儿,我们的配置自定义的starter就写完了 ,我们hello-spring-boot-starter-autoconfigurer、hello-spring-boot-starter 安装成本地jar包。

三、测试自定义starter

我们创建个项目 hello-spring-boot-starter-test,来测试系我们写的stater。

1. pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.gf</groupId>
  6. <artifactId>hello-spring-boot-starter-test</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>hello-spring-boot-starter-test</name>
  10. <description>Demo project for Spring Boot</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>1.5.9.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <!-- 引入自定义starter -->
  28. <dependency>
  29. <groupId>com.gf</groupId>
  30. <artifactId>hello-spring-boot-starter</artifactId>
  31. <version>0.0.1-SNAPSHOT</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. </dependencies>
  39. <build>
  40. <plugins>
  41. <plugin>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-maven-plugin</artifactId>
  44. </plugin>
  45. </plugins>
  46. </build>
  47. </project>

2. HelloController

  1. package com.gf.controller;
  2. import com.gf.service.HelloService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. public class HelloController {
  9. @Autowired
  10. HelloService helloService;
  11. @GetMapping("/hello/{name}")
  12. public String hello(@PathVariable(value = "name") String name) {
  13. return helloService.sayHello( name + " , " );
  14. }
  15. }

3. application.properties

  1. gf.hello.prefix = hi
  2. gf.hello.suffix = what's up man ?

我运行项目访问 http://127.0.0.1:8080/hello/zhangsan,结果如下:

  1. hi-zhangsan , what's up man ?

源码下载: https://github.com/gf-huanchupk/SpringBootLearning

欢迎扫码或微信搜索公众号《程序员果果》关注我,关注有惊喜~

Spring Boot 自定义 starter的更多相关文章

  1. Spring Boot自定义starter必知必会条件

    前言 在目前的Spring Boot框架中,不管是Spring Boot官方还是非官方,都提供了非常多的starter系列组件,助力开发者在企业应用中的开发,提升研发人员的工作效率,Spring Bo ...

  2. spring boot自定义starter

    1.spring boot 项目中自定义jar包 2.项目目录 3.src/main/java 下面写自己的方法,重点是 resources 下面的文件,在resources下面新建文件夹名字为 ME ...

  3. Spring boot 自定义starter

    以下配置来自尚硅谷.. 常用如何配置 @Configuration //指定这个类是一个配置类 @ConditionalOnXXX //在指定条件成立的情况下自动配置类生效 @AutoConfigur ...

  4. Spring Boot 自定义Starter 可能引发的问题(Error)

    如果你的项目出现: Consider defining a bean of type 'com.wy.helloworld_spring_boot_starter.PersonService' in ...

  5. 【串线篇】spring boot自定义starter

    starter: 一.这个场景需要使用到的依赖是什么? 二.如何编写自动配置 启动器只用来做依赖导入:(启动器模块是一个空 JAR 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库) ...

  6. spring boot自定义线程池以及异步处理

    spring boot自定义线程池以及异步处理@Async:什么是线程池?线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线程池线程都是后台线程.每个线程都使 ...

  7. Spring Boot自定义配置与加载

    Spring Boot自定义配置与加载 application.properties主要用来配置数据库连接.日志相关配置等.除了这些配置内容之外,还可以自定义一些配置项,如: my.config.ms ...

  8. Spring Boot 2.X(四):Spring Boot 自定义 Web MVC 配置

    0.准备 Spring Boot 不仅提供了相当简单使用的自动配置功能,而且开放了非常自由灵活的配置类.Spring MVC 为我们提供了 WebMvcConfigurationSupport 类和一 ...

  9. Spring Boot自定义Redis缓存配置,保存value格式JSON字符串

    Spring Boot自定义Redis缓存,保存格式JSON字符串 部分内容转自 https://blog.csdn.net/caojidasabi/article/details/83059642 ...

随机推荐

  1. C#8.0可空引用类型的使用注意要点

    最近VS2019正式版发布了,装下来顺便试用了一下C#8.0,最大的看点应该就是可空引用类型了.不过C#8.0仍然处于Beta的状态,而且试用时也遇到了几个坑. 背景知识说明: 所谓的可空引用类型是指 ...

  2. .netcoreapp 发布到 linux 的问题,vs靠不住

    .netcore 2.0 发布后,小版本更新速度惊人 截止目前:2.1.200 最新一个新项目,vs发布到linux@debian9一直报错,反复发布n次依然失败.把本地2.1.100更新到最新2.1 ...

  3. Vue2.0源码阅读笔记(三):计算属性

      计算属性是基于响应式依赖进行缓存的,只有在相关响应式依赖发生改变时才会重新求值,这种缓存机制在求值消耗比较大的情况下能够显著提高性能. 一.计算属性初始化   Vue 在做数据初始化时,通过 in ...

  4. Caffe源码理解1:Blob存储结构与设计

    博客:blog.shinelee.me | 博客园 | CSDN Blob作用 据Caffe官方描述: A Blob is a wrapper over the actual data being p ...

  5. MySQL5.7下面,误操作导致的drop table db1.tb1; 的恢复方法:

    MySQL5.7下面,误操作导致的drop table db1.tb1; 的恢复方法: 0.停业务数据写入.[iptables封禁] 1.从备份服务器上拉取最新的一个全备文件,恢复到一个临时的服务器上 ...

  6. 零基础学Python--------第3章 流程控制语句

    第3章 流程控制语句 3.1程序的结构 计算机在解决某个具体问题时,主要有3种情况,分别是顺序执行所有的语句.选择执行部分语句和循环执行部分语句.程序设计中的3种基本结构为顺序结构.选择结构和循环结构 ...

  7. geodocker-geomesa安装指南

        最近研究geopyspark原本以为大数据研究能告一段落,因为...     开玩笑的,还要一起建设社会主义呢!! 背景     geotrellis作为一个处理遥感数据的框架,对于遥感数据支 ...

  8. git tag本地删除以及远程删除

    假设存在tag:12345 git tag -d 12345 #删除本地记录 git push origin :refs/tags/12345 #删除远程记录 PS: 如果您觉得我的文章对您有帮助,可 ...

  9. Windows系统ping本地虚拟机~

    虚拟机左上角[编辑]>>>[虚拟网络编辑器] [VMnet1]>>>子网ip:192.168.124.0 子网掩码:255.255.255.0 [VMnet8]&g ...

  10. SQL server 存储过程的建立和调用

     存储过程的建立和调用 --1.1准备测试需要的数据库:test,数据表:物料表,采购表if not exists (select * from master.dbo.sysdatabases whe ...