前些日子在公司接触了spring bootspring cloud,有感于其大大简化了spring的配置过程,十分方便使用者快速构建项目,而且拥有丰富的starter供开发者使用。但是由于其自动化配置的原因,往往导致出现问题,新手无法快速定位问题。这里我就来总结一下spring boot 自定义starter的过程,相信大家看完这篇文章之后,能够对spring boot starter的运行原理有了基本的认识。
 为了节约你的时间,本篇文章的主要内容有:

  • spring boot starter的自定义
  • spring boot auto-configuration的两种方式,spring.factories和注解
  • Conditional注解的使用

引入pom依赖

相信接触过spring boot的开发者都会被其丰富的starter所吸引,如果你想给项目添加redis支持,你就可以直接引用spring-boot-starter-redis,如果你想使项目微服务化,你可以直接使用spring-cloud-starter-eureka。这些都是spring boot所提供的便利开发者的组件,大家也可以自定义自己的starter并开源出去供开发者使用。
 创建自己的starter项目需要maven依赖是如下所示:

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.4.4.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>

核心配置类StorageAutoConfigure

构建starter的关键是编写一个装配类,这个类可以提供该starter核心bean。这里我们的starter提供一个类似redis的键值存储功能的bean,我们叫它为StorageService。负责对这个bean进行自动化装配的类叫做StorageAutoConfigure。保存application.properties配置信息的类叫做StorageServiceProperties。这三种类像是铁三角一样,你可以在很多的spring-boot-starter中看到他们的身影。
 我们首先来看StorageAutoConfigure的定义。

@Configuration
@ConditionalOnClass(StorageService.class)
@EnableConfigurationProperties(StorageServiceProperties.class)
public class StorageAutoConfigure {
@Autowired
private StorageServiceProperties properties; @Bean
@ConditionalOnMissingBean(StorageService.class)
@ConditionalOnProperty(prefix = "storage.service", value = "enabled", havingValue = "true")
StorageService exampleService() {
return new StorageService(properties);
}
}

我们首先讲一下源码中注解的作用。

  • @Configuration,被该注解注释的类会提供一个或则多个@bean修饰的方法并且会被spring容器处理来生成bean definitions
  • @bean注解是必须修饰函数的,该函数可以提供一个bean。而且该函数的函数名必须和bean的名称一致,除了首字母不需要大写。
  • @ConditionalOnClass注解是条件判断的注解,表示对应的类在classpath目录下存在时,才会去解析对应的配置文件。
  • @EnableConfigurationProperties注解给出了该配置类所需要的配置信息类,也就是StorageServiceProperties类,这样spring容器才会去读取配置信息到StorageServiceProperties对象中。
  • @ConditionalOnMissingBean注解也是条件判断的注解,表示如果不存在对应的bean条件才成立,这里就表示如果已经有StorageService的bean了,那么就不再进行该bean的生成。这个注解十分重要,涉及到默认配置和用户自定义配置的原理。也就是说用户可以自定义一个StorageService的bean,这样的话,spring容器就不需要再初始化这个默认的bean了。
  • ConditionalOnProperty注解是条件判断的注解,表示如果配置文件中的响应配置项数值为true,才会对该bean进行初始化。

看到这里,大家大概都明白了StorageAutoConfigure的作用了吧,spring容器会读取相应的配置信息到StorageServiceProperties中,然后依据调节判断初始化StorageService这个bean。集成了该starter的项目就可以直接使用StorageService来存储键值信息了。

配置信息类StorageServiceProperties

存储配置信息的类StorageServiceProperties很简单,源码如下所示:

@ConfigurationProperties("storage.service")
public class StorageServiceProperties {
private String username;
private String password;
private String url; ......
//一系列的getter和setter函数
}

@ConfigurationProperties注解就是让spring容器知道该配置类的配置项前缀是什么,上述的源码给出的配置信息项有storage.service.username,storage.service.passwordstorage.service.url,类似于数据库的host和用户名密码。这些配置信息都会由spring容器从application.properties文件中读取出来设置到该类中。

starter提供功能的StorageService

StorageService类是提供整个starter的核心功能的类,也就是提供键值存储的功能。

public class StorageService {
private Logger logger = LoggerFactory.getLogger(StorageService.class);
private String url;
private String username;
private String password;
private HashMap<String, Object> storage = new HashMap<String, Object>();
public StorageService(StorageServiceProperties properties) {
super();
this.url = properties.getUrl();
this.username = properties.getUsername();
this.password = properties.getPassword();
logger.debug("init storage with url " + url + " name: " + username + " password: " + password);
} public void put(String key, Object val) {
storage.put(key, val);
} public Object get(String key) {
return storage.get(key);
}
}

注解配置和spring.factories

 自定义的starter有两种方式来通知spring容器导入自己的auto-configuration类,也就是本文当中的StorageAutoConfigure类。
 一般都是在starter项目的resources/META-INF文件夹下的spring.factories文件中加入需要自动化配置类的全限定名称。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=starter.StorageAutoConfigure

spring boot项目中的EnableAutoConfigurationImportSelector会自动去每个jar的相应文件下查看spring.factories文件内容,并将其中的类加载出来在auto-configuration过程中进行配置。而EnableAutoConfigurationImportSelector@EnableAutoConfiguration注解中被import
 第一种方法只要是引入该starter,那么spring.factories中的auto-configuration类就会被装载,但是如果你希望有更加灵活的方式,那么就使用自定义注解来引入装配类。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(StorageAutoConfigure.class)
@Documented
public @interface EnableStorage {
}

 有了这个注解,你可以在你引入该starter的项目中使用该注解,通过@import注解,spring容器会自动加载StorageAutoConfigure并自动化进行配置。

后记

作者:ztelur
链接:https://www.jianshu.com/p/4735fe7ae921
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

==
 
https://juejin.im/entry/58d37630570c350058c2c15c

Spring Boot (一): Spring Boot starter自定义的更多相关文章

  1. Spring Boot必备技能之Starter自定义

    本文摘自于<Spring Cloud微服务 入门 实战与进阶>一书.  作者:尹吉欢 Spring Boot的方便体现在简化了很多繁琐的配置,对开发人员来说是一个福音,通过引入各种Spri ...

  2. 让Spring Boot项目启动时可以根据自定义配置决定初始化哪些Bean

    让Spring Boot项目启动时可以根据自定义配置决定初始化哪些Bean 问题描述 实现思路 思路一 [不符合要求] 思路二[满足要求] 思路三[未试验] 问题描述 目前我工作环境下,后端主要的框架 ...

  3. Spring Boot 2.X(十):自定义注册 Servlet、Filter、Listener

    前言 在 Spring Boot 中已经移除了 web.xml 文件,如果需要注册添加 Servlet.Filter.Listener 为 Spring Bean,在 Spring Boot 中有两种 ...

  4. spring boot集成mybatis-plus插件进行自定义sql方法开发时报nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

    spring boot集成mybatis-plus插件进行自定义sql方法开发时报nested exception is org.apache.ibatis.binding.BindingExcept ...

  5. Spring MVC和Spring Boot的理解以及比较

    Spring MVC是什么?(1)Spring MVC是Spring提供的一个强大而灵活的模块式web框架.通过Dispatcher Servlet, ModelAndView 和 View Reso ...

  6. Spring Boot实践——Spring Boot 2.0 新特性和发展方向

    出自:https://mp.weixin.qq.com/s/EWmuzsgHueHcSB0WH-3AQw 以Java 8 为基准 Spring Boot 2.0 要求Java 版本必须8以上, Jav ...

  7. Spring boot与Spring cloud之间的关系

    Spring boot 是 Spring 的一套快速配置脚手架,可以基于spring boot 快速开发单个微服务,Spring Boot,看名字就知道是Spring的引导,就是用于启动Spring的 ...

  8. Redis篇之操作、lettuce客户端、Spring集成以及Spring Boot配置

    Redis篇之操作.lettuce客户端.Spring集成以及Spring Boot配置 目录 一.Redis简介 1.1 数据结构的操作 1.2 重要概念分析 二.Redis客户端 2.1 简介 2 ...

  9. 使用Spring Session实现Spring Boot水平扩展

    小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...

随机推荐

  1. java操作数据库:分页查询

    直接上.... 还是用之前的goods表,增加了一些数据 1.实体类Goods // 封装数据 public class Goods { private int gid; private String ...

  2. python中的optionParser模块

    Python 有两个内建的模块用于处理命令行参数:一个是 getopt,<Deep in python>一书中也有提到,只能简单处理 命令行参数:另一个是 optparse,它功能强大,而 ...

  3. BN_batch normalization

    参考: https://zhuanlan.zhihu.com/p/27938792 做法 设,每个batch输入是 (其中每个 都是一个样本, 是batch size) 假如在第一层后加入Batch ...

  4. C语言编程程序的内存如何布局

    重点关注以下内容: C语言程序在内存中各个段的组成 C语言程序连接过程中的特性和常见错误 C语言程序的运行方式 一:C语言程序的存储区域 由C语言代码(文本文件)形成可执行程序(二进制文件),需要经过 ...

  5. CentOS7.2通过Yum安装MySQL5.7

    1 下载源 wget http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm 2安装源 yum localinstall ...

  6. Linq中的left join

    left join var custs = from c in db.T_Customer join u in db.Sys_User on c.OwnerId equals u.Id into te ...

  7. 最全的jquery datatables api 使用详解

    学习可参考:http://www.guoxk.com/node/jquery-datatables http://yuemeiqing2008-163-com.iteye.com/blog/20069 ...

  8. Python 爬虫一 简介

    什么是爬虫? 爬虫可以做什么? 爬虫的本质 爬虫的基本流程 什么是request&response 爬取到数据该怎么办 什么是爬虫? 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间 ...

  9. 在IDEA中新建Spring Boot项目

    新建项目 选择项目构建方式 选择项目依赖 新建项目成功后(Maven构建方式)

  10. EL表达式 EL函数 自定义el函数 《黑马程序员_超全面的JavaWeb视频教程vedio》

    \JavaWeb视频教程_day12_自定义标签JSTL标签库,java web之设计模式\day12_avi\12.EL入门.avi; EL表达式 1. EL是JSP内置的表达式语言! * jsp2 ...