前些日子在公司接触了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依赖是如下所示:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-autoconfigure</artifactId>
  4. <version>1.4.4.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-configuration-processor</artifactId>
  9. <version>1.4.4.RELEASE</version>
  10. </dependency>

核心配置类StorageAutoConfigure

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

  1. @Configuration
  2. @ConditionalOnClass(StorageService.class)
  3. @EnableConfigurationProperties(StorageServiceProperties.class)
  4. public class StorageAutoConfigure {
  5. @Autowired
  6. private StorageServiceProperties properties;
  7. @Bean
  8. @ConditionalOnMissingBean(StorageService.class)
  9. @ConditionalOnProperty(prefix = "storage.service", value = "enabled", havingValue = "true")
  10. StorageService exampleService() {
  11. return new StorageService(properties);
  12. }
  13. }

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

  • @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很简单,源码如下所示:

  1. @ConfigurationProperties("storage.service")
  2. public class StorageServiceProperties {
  3. private String username;
  4. private String password;
  5. private String url;
  6. ......
  7. //一系列的getter和setter函数
  8. }

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

starter提供功能的StorageService

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

  1. public class StorageService {
  2. private Logger logger = LoggerFactory.getLogger(StorageService.class);
  3. private String url;
  4. private String username;
  5. private String password;
  6. private HashMap<String, Object> storage = new HashMap<String, Object>();
  7. public StorageService(StorageServiceProperties properties) {
  8. super();
  9. this.url = properties.getUrl();
  10. this.username = properties.getUsername();
  11. this.password = properties.getPassword();
  12. logger.debug("init storage with url " + url + " name: " + username + " password: " + password);
  13. }
  14. public void put(String key, Object val) {
  15. storage.put(key, val);
  16. }
  17. public Object get(String key) {
  18. return storage.get(key);
  19. }
  20. }

注解配置和spring.factories

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

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

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

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Import(StorageAutoConfigure.class)
  4. @Documented
  5. public @interface EnableStorage {
  6. }

 有了这个注解,你可以在你引入该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动态代理 深度详解

    代理模式是设计模式中非常重要的一种类型,而设计模式又是编程中非常重要的知识点,特别是在业务系统的重构中,更是有举足轻重的地位.代理模式从类型上来说,可以分为静态代理和动态代理两种类型. 今天我将用非常 ...

  2. extjs.net Combox赋值

    1.直接赋值 ].Rows) //遍历获取两个值 { Ext.Net.ListItem listItem = new Ext.Net.ListItem(); //每次创建一个Ext.Net.ListI ...

  3. NFine框架JqGrid导出选中行为Excel实现方法

    客户端 function PostAndGetFileByUrl(url,type,postdata) { var temp; $.ajax({ url: url, type: type, data: ...

  4. 俄罗斯方块部分功能(Java)

    package OO.day01; public class TetrisCell { int totalRow = 20; int totalcol = 10; //定义横宽 int row; in ...

  5. alexnet- tensorflow

    alexnet 在 imagenet上夺冠是卷积神经网络如今这么火热的起点. 虽然卷积神经网络很早就被提出来,但是由于计算能力和各方面原因,没有得到关注. alexnet 为什么能取得这么好的成绩,它 ...

  6. sum() over (order by )

    sum(x) over( partition by y ORDER BY z ) 分析 sum(x) over (partition by y order by z) 求安照y分区,然后按z排序,连续 ...

  7. 进程池爬取并存入mongodb

    设置进程池爬取拉钩网: # coding = utf- import json import pymongo import pandas as pd import requests from lxml ...

  8. JDK开发环境搭建及环境变量配置

    Java配置----JDK开发环境搭建及环境变量配置 1. 下载安装安装JDK开发环境 http://www.oracle.com/technetwork/java/javase/downloads/ ...

  9. Leetcode#53.Maximum Subarray(最大子序和)

    题目描述 给定一个序列(至少含有 1 个数),从该序列中寻找一个连续的子序列,使得子序列的和最大. 例如,给定序列 [-2,1,-3,4,-1,2,1,-5,4], 连续子序列 [4,-1,2,1] ...

  10. ES6 基础

    转载自:ES6 基础 一.新的变量声明方式 let/const 与var不同,新的变量声明方式带来了一些不一样的特性,其中最重要的两个特性就是提供了块级作用域与不再具备变量提升. 通过2个简单的例子来 ...