Spring Boot - 自定义starter

2024-06-08 08:38

本文主要是介绍Spring Boot - 自定义starter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 运行原理

关于Spring Boot的运行原理,还是要回归到@SpringBootApplication注解上来,此注解是一个组合注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
...
}

核心功能是由@EnableAutoConfiguration提供的。其源码如下。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
...
}

这里的关键是由@Import注解导入的配置功能,借助EnableAutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助Spring Boot应用将所有符合条件的@Configuration配置都加载到当前Spring Boot创建并使用的IoC容器中。借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持,使用其loadFactoryNames方法来扫描具有META-INF/spring.factories文件的jar包,而spring-boot-autoconfigure-1.5.2.RELEASE.jar包里就有此文件,此文件里声明了大量的自动配置:
在这里插入图片描述

2.核心注解

任意打开上面一个Auto Configure文件,一般都有条件注解,以@ConditionalOn…开头的注解,如:

    //当类路径下有指定的条件@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class })//指定的属性是否有执行的值@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)//当前项目时web项目的条件下@ConditionalOnWebApplication//等等 ...

此处简单的分析一下@ConditionalOnWebApplication的实现,看看这个条件是如何构造的。

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnWebApplicationCondition.class)
public @interface ConditionalOnWebApplication {}

进入到其代码OnWebApplicationCondition查看,有以下几个判断条件,最终通过ConditionOutcome类的对象返回boolean来判断。

@Order(Ordered.HIGHEST_PRECEDENCE + 20)
class OnWebApplicationCondition extends SpringBootCondition {private static final String WEB_CONTEXT_CLASS = "org.springframework.web.context."+ "support.GenericWebApplicationContext";@Overridepublic ConditionOutcome getMatchOutcome(ConditionContext context,AnnotatedTypeMetadata metadata) {boolean required = metadata.isAnnotated(ConditionalOnWebApplication.class.getName());ConditionOutcome outcome = isWebApplication(context, metadata, required);if (required && !outcome.isMatch()) {return ConditionOutcome.noMatch(outcome.getConditionMessage());}if (!required && outcome.isMatch()) {return ConditionOutcome.noMatch(outcome.getConditionMessage());}return ConditionOutcome.match(outcome.getConditionMessage());}private ConditionOutcome isWebApplication(ConditionContext context,AnnotatedTypeMetadata metadata, boolean required) {ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class, required ? "(required)" : "");//判断条件:WEB_CONTEXT_CLASS 是否在类路径中if (!ClassUtils.isPresent(WEB_CONTEXT_CLASS, context.getClassLoader())) {return ConditionOutcome.noMatch(message.didNotFind("web application classes").atAll());}//判断条件:容器里是否有名为session的scopeif (context.getBeanFactory() != null) {String[] scopes = context.getBeanFactory().getRegisteredScopeNames();if (ObjectUtils.containsElement(scopes, "session")) {return ConditionOutcome.match(message.foundExactly("'session' scope"));}}//判断条件:容器的Environment是否是StandardServletEnvironmentif (context.getEnvironment() instanceof StandardServletEnvironment) {return ConditionOutcome.match(message.foundExactly("StandardServletEnvironment"));}//判断条件:ResourceLoader是否是WebApplicationContextif (context.getResourceLoader() instanceof WebApplicationContext) {return ConditionOutcome.match(message.foundExactly("WebApplicationContext"));}return ConditionOutcome.noMatch(message.because("not a web application"));}}

3.example starter实战

  1. 新建Maven项目,pom文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>example-spring-boot-starter</artifactId><version>1.0</version><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><!-- Import dependency management from Spring Boot --><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>1.5.2.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
</project>
  1. 属性代码
package com.example.autoconfigure;import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties("example.service")
public class ExampleServiceProperties {private String prefix;private String suffix;public String getPrefix() {return prefix;}public void setPrefix(String prefix) {this.prefix = prefix;}public String getSuffix() {return suffix;}public void setSuffix(String suffix) {this.suffix = suffix;}
}
  1. 自动配置类
package com.example.autoconfigure;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
//此类存在时自动配置这个bean
@ConditionalOnClass(ExampleService.class)
@EnableConfigurationProperties(ExampleServiceProperties.class)
public class ExampleAutoConfigure {private final ExampleServiceProperties properties;@Autowiredpublic ExampleAutoConfigure(ExampleServiceProperties properties) {this.properties = properties;}@Bean@ConditionalOnMissingBean//参数enabled为true才可以配置ExampleService @ConditionalOnProperty(prefix = "example.service", value = "enabled", havingValue = "true")ExampleService exampleService() {return new ExampleService(properties.getPrefix(), properties.getSuffix());}}
  1. ExampleService类及方法
package com.example.autoconfigure;public class ExampleService {private String prefix;private String suffix;public ExampleService(String prefix, String suffix) {this.prefix = prefix;this.suffix = suffix;}public String wrap(String word) {return prefix + word + suffix;}
}
  1. 注册配置
    若想自动配置生效,需要注册自动配置类。在\src\main\resources目录下建文件\META-INF\spring.factories,并填写如下注册内容:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.autoconfigure.ExampleAutoConfigure

此时项目结构如下所示:
在这里插入图片描述
我们可以使用mvn install将其安装到本地库,在其他项目中引入后进行使用。

  1. 使用demo

步骤类似于使用其他starter,首先引入依赖:

       <dependency><groupId>com.example</groupId><artifactId>example-spring-boot-starter</artifactId><version>1.0</version></dependency>

要注意的是, //参数enabled为true才可以配置ExampleService,所以我们要在配置文件中加上

example.service:enabled: trueprefix: (suffix: )

相当于手动加一个开关(这里只是为了演示默认,并无太大意义),否则会有如下错误:

***************************
APPLICATION FAILED TO START
***************************Description:Field exampleService in com.kyee.nqm.commons.controller.DemoController required a bean of type 'com.example.autoconfigure.ExampleService' that could not be found.- Bean method 'exampleService' in 'ExampleAutoConfigure' not loaded because @ConditionalOnProperty (example.service.enabled=true) did not find property 'enabled'Action:Consider revisiting the conditions above or defining a bean of type 'com.example.autoconfigure.ExampleService' in your configuration.

装配及使用:

    @AutowiredExampleService exampleService;@GetMapping("/exampleService")public Response exampleService() {return Response.success(exampleService.wrap(" hello world "));}

然后调用此接口,可以看到,输入的 hello world 被包裹了一对(),我们的starter可以正常使用了。:)
在这里插入图片描述

这篇关于Spring Boot - 自定义starter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1041686

相关文章

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.