前些日子在公司接触了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. PHP 调第三方跨域接口示例

    <?php ); //错误信息 ); //php启动错误信息 ini_set('date.timezone','Asia/Shanghai'); ); //打印出所有的 错误信息 ini_set ...

  2. 二十六、Linux 进程与信号---system 函数 和进程状态切换

    26.1 system 函数 26.1.1 函数说明 system(执行shell 命令)相关函数 fork,execve,waitpid,popen #include <stdlib.h> ...

  3. 【Ubuntu】安装Java和Eclipse

    1. 安装Java 1> sudo add-apt-repository ppa:webupd8team/java 2> sudo apt-get update 3> sudo ap ...

  4. springboot11-security02FromDB 权限管理(用户信息和角色信息保存在数据库)

    <h4>场景</h4> <h4>代码</h4> springboot+springsecurity+mysql(jpa)实现: 1.pom依赖: < ...

  5. js获取网页面的高度和宽度

    网页可见区域宽:document.body.clientWidth网页可见区域高:document.body.clientHeight网页可见区域宽:document.body.offsetWidth ...

  6. tensorflow can not find libcusolver.so.8.0

    ImportError: libcusolver.so.8.0: cannot open shared object file: No such file or directory solution: ...

  7. VGG-16详解

    VGG16输入224*224*3的图片,经过的卷积核大小为3x3x3,stride=1,padding=1,pooling为采用2x2的max pooling方式: 1.输入224x224x3的图片, ...

  8. TF, IDF和TF-IDF

    在相似文本的推荐中,可以用TF-IDF来衡量文章之间的相似性. 一.TF(Term Frequency) TF的含义很明显,就是词出现的频率. 公式: 在算文本相似性的时候,可以采用这个思路,如果两篇 ...

  9. [C++]数组处理相关函数(memcpy/memset等)

    头文件:string.h或者memory.h [1]void *memcpy(void *dest, const void *src, size_t n);//数组元素拷贝 功能:从源src所指的内存 ...

  10. 如何发布自己的 jar 包到 maven 中央仓库(待更新...)

    参考链接 如何发布自己的 jar 包到 maven 中央仓库