spring-core源码走读

Spring-core 5.0.8

asm

  • ASM is an all purpose Java bytecode manipulation and analysis framework.

  • ASM是一个万能的java字节码操纵和分析框架

cglib

  • Byte Code Generation Library is high level API to generate and transform JAVA byte code

  • 高层级的生成和转换Java字节码的字节码生成库

objenesis

  • Objenesis is a small Java library that serves one purpose:To instantiate a new object of a particular class.

  • Objenesis是一个只为特殊类初始化对象小型Java库

lang

  • 定义八个注解

    • NonNull.class

    • NonNullApi.class

    • NonNullFields.class

    • Nullable.class

    • UsesJava7.class

    • UsesJava8.class

    • UsesSunHttpServer.class

    • UsesSunMisc.class

util

backoff

重试算法

  • 定义退避算法

    • BackOff.class

    • BackOffExecution.class

    • ExponentialBackOff.class 指数重试间隔实现

    • FixedBackOff.class 固定重试间隔实现

  • 用于封装重试逻辑

使用说明

 BackOffExecution exec = backOff.start();

// In the operation recovery/retry loop:
long waitInterval = exec.nextBackOff();
if (waitInterval == BackOffExecution.STOP) {
    // do not retry operation
}
else {
    // sleep, e.g. Thread.sleep(waitInterval)
    // retry operation
}
}

测试代码

package com.zby.util.backoff;

import java.util.Date;

import org.springframework.util.backoff.BackOff;
import org.springframework.util.backoff.BackOffExecution;
import org.springframework.util.backoff.ExponentialBackOff;
import org.springframework.util.backoff.FixedBackOff;

public class BackoffDemo {

public static void main(String[] args) throws Exception {
//BackOff backOff = new FixedBackOff(1000, 10);
BackOff backOff = new ExponentialBackOff(500, 2);
BackOffExecution backOffExecution = backOff.start();
int successTime=7;
for(int i=0;;i++) {
System.out.println("重试:"+backOffExecution);
long waitInterval = backOffExecution.nextBackOff();
if (waitInterval == BackOffExecution.STOP) {
System.out.println("执行失败:" + backOffExecution);
break;
} else {
Thread.sleep(waitInterval);
System.out.println("准备执行操作,当前时间:"+new Date());
boolean success = operation(successTime==i);
if(success) {
break;
}
}
}

}

public static boolean operation(boolean success) {
System.out.println("执行结果:"+success);
return success;
}

}
  • 可以封装一下把公共代码封装起来,提供重试机制,如:

package com.zby.util.backoff;

import java.util.Date;

import org.springframework.util.backoff.BackOff;
import org.springframework.util.backoff.BackOffExecution;
import org.springframework.util.backoff.FixedBackOff;

public abstract class FixedBackOffRunnable implements Runnable{

private BackOffExecution backOffExecution;

public FixedBackOffRunnable(long interval, long maxAttempts) {
BackOff backOff = new FixedBackOff(interval, maxAttempts);
backOffExecution = backOff.start();

}

public void run() {
while (true) {
System.out.println("重试:" + backOffExecution);
long waitInterval = backOffExecution.nextBackOff();
if (waitInterval == BackOffExecution.STOP) {
System.out.println("执行失败:" + backOffExecution);
break;
} else {
try {
Thread.sleep(waitInterval);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("准备执行操作,当前时间:" + new Date());
boolean retry=false;
try {
doRun();
} catch (RetryableExeception e) {
retry=true;
}
if(!retry) {
break;
}
}
}
}

public abstract void doRun() throws RetryableExeception;
}
​或者使用装饰模式,命令模式,aop方式实现等

comparator

比较相关工具

  • 定义常用comparator实现

    • BooleanComparator.class

    • ComparableComparator.class 封装实现了Comparable接口的对象的comparator

    • Comparators.class

    • CompoundComparator.class

    • InstanceComparator.class

    • InvertibleComparator.class

    • NullSafeComparator.class 封装一个未处理null比较的comparator

concurrent

  • 拓展JDK的Future,主要添加监听任务执行机制,在core的task包使用

xml

  • 封装xml相关工具类

IdGenerator.java

  • 生成JDK的UUID

  • JdkIdGenerator 直接使用UUID.randomUUID()

  • SimpleIdGenerator

  • AlternativeJdkIdGenerator

PathMatcher.java

  • 路径匹配器

  • AntPathMatcher ant风格的路径匹配器

    • The mapping matches URLs using the following rules:

      • ? matches one character

      • * matches zero or more characters

      • ** matches zero or more directories in a path

      • ` {spring:[a-z]+}} matches the regexp[a-z]+` as a path variable named "spring"

Assert.java

  • 断言工具类

  • state(boolean expression, String message)

  • isTrue(boolean expression, String message)

  • isNull(@Nullable Object object, String message)

  • notNull(@Nullable Object object, String message)

  • hasLength(@Nullable String text, String message)

  • hasText(@Nullable String text, String message)

  • doesNotContain(@Nullable String textToSearch, String substring, String message)

  • notEmpty(@Nullable Object[] array, String message)

  • noNullElements(@Nullable Object[] array, String message)

  • notEmpty(@Nullable Collection<?> collection, String message)

  • notEmpty(@Nullable Map<?, ?> map, String message)

  • isInstanceOf(Class<?> type, @Nullable Object obj, String message)

  • isAssignable(Class<?> superType, @Nullable Class<?> subType, String message)

AutoPopulatingList.java

  • 自动填充的List

  • 根据索引获取元素的时候,如果没有,创建一个对象返回

  • E get(int index) 永远不会返回null

  • 默认通过反射创建,所以元素需要有无参构造方法

Base64Utils.java

  • base64工具类

ClassUtils.java

  • class工具类

CollectionUtils.java

  • 集合工具类

CommonsLogWriter.java

  • org.apache.commons.logging.Log适配为JDK的Writer

CompositeIterator.java

  • 组合迭代器

  • 可以添加多个迭代器,统一顺序迭代

  • 组合模式

ConcurrencyThrottleSupport.java

  • 并发限流支持,core的task包下有使用

  • 继承这个类可以实现对资源访问限流

  • 在访问资源前调用beforeAccess,访问后调用afterAccess

ConcurrentReferenceHashMap.java

  • 支持key和value的Soft引用和Weak引用

  • 默认Soft引用

  • 类似ConcurrentHashMap实现,但是支持key和value为null

CustomizableThreadCreator.java

  • 自定义的线程创建器

PropertiesPersister.java

  • Properties持久化器

  • DefaultPropertiesPersister 默认实现直接调用Properties响应方法

DigestUtils.java

  • 摘要工具类

  • 只提供了MD5相关的摘要工具方法

ErrorHandler.java

  • 错误处理器

InstanceFilter.java

  • 实例过滤器

  • ExceptionTypeFilter 异常实例过滤器

FastByteArrayOutputStream.java

  • 使用LinkedList<byte[]>存放数据

  • 扩容时不会发生数据拷贝,直接新增一个byte[]

  • 继承OutputStream而不是ByteArrayOutputStream

ResizableByteArrayOutputStream.java

  • 可手动扩容的ByteArrayOutputStream

  • 继承ByteArrayOutputStream

  • 默认初始容量256,ByteArrayOutputStream默认初始容量32

FileCopyUtils.java

  • 文件拷贝工具类

FileSystemUtils.java

  • 文件系统工具类

  • 提供递归删除和拷贝方法

LinkedCaseInsensitiveMap.java

  • 大小写不敏感的LinkedHashMap

MultiValueMap.java

  • 具有多个值的Map

LinkedMultiValueMap.java

  • 具有多个value的LinkedHashMap

  • 实现MultiValueMap

MethodInvoker.java

  • 方法执行器

  • 封装类方法或实例方法的执行

MimeType.java

  • MIME (Multipurpose Internet Mail Extensions) 是描述消息内容类型的因特网标准

  • 参考手册

  @Test
void parseQuotedSeparator() {
String s = "application/xop+xml;charset=utf-8;type=\"application/soap+xml;action=\\\"https://x.y.z\\\"\"";
MimeType mimeType = MimeType.valueOf(s);
assertThat(mimeType.getType()).as("Invalid type").isEqualTo("application");
assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("xop+xml");
assertThat(mimeType.getCharset()).as("Invalid charset").isEqualTo(StandardCharsets.UTF_8);
assertThat(mimeType.getParameter("type")).isEqualTo("\"application/soap+xml;action=\\\"https://x.y.z\\\"\"");
}

MimeTypeUtils.java

  • 定义常用常量和解析方法

NumberUtils.java

  • Number子类相关解析

ObjectUtils.java

  • Object类的工具类

  • 类型安全的toString和hashCode方法

PatternMatchUtils.java

  • 模式匹配工具类

  • 提供简单的*匹配

PropertyPlaceholderHelper.java

  • 属性占位符帮助类

  • 替换字符串占位符,支持使用默认值

ReflectionUtils.java

  • 反射工具类

ResourceUtils.java

  • 资源工具类

SerializationUtils.java

  • JDK序列化工具类

SocketUtils.java

  • TCP和UDP端口查找工具方法

StopWatch.java

  • 程序运行记录器,记录任务执行时间

StreamUtils.java

  • 流拷贝相关工具类

StringUtils.java

  • 字符串相关工具类

SystemPropertyUtils.java

  • 使用系统属性解析字符串占位符工具类

TypeUtils.java

core

task

  • 依赖concurrent包提供的可监听Future扩展

  • 支持并发访问线程限流

  • 支持任务装饰,比如统一记录每个任务的运行时间

  • AsyncListenableTaskExecutor

style

  • toString相关的构建器

    • DefaultToStringStyler.class

    • DefaultValueStyler.class

    • StylerUtils.class

    • ToStringCreator.class

    • ToStringStyler.class

    • ValueStyler.class

Serializer

  • 序列化相关类

  • 实现JDK序列化

  • Object<—>byte[]的Converter

io

  • Resource相关接口,实现,工具类

  • DataBuffer封装

codec

  • 编解码

converter

  • Converter、GenericConverter、ConverterFactory转换具体实现

  • ConverterRegistry转换器注册中心

  • ConversionService提供统一的用户接口,DefaultConversionService默认实现

env

  • PropertyResolver属性解析器

  • 依赖ConversionService做类型转换

  • PropertySource代表不同属性源,PropertySourcesPropertyResolver依赖PropertySource解析属性

  • Environment提供统一的用户接口

type

  • 定义获取类元数据的接口

    • AnnotatedTypeMetadata.class

    • AnnotationMetadata.class

    • ClassMetadata.class

    • MethodMetadata.class

  • 标准实现使用Class和Method进行获取,也就是类已经加载

  • classreading包基于ASM实现可以直接读取class文件,获取类信息,不加载类

  • filter包定义Type过滤器,读取到大量的类元数据可以通过过滤器过滤出想要的类,比如扫描一个包下面有Configuration注解的所有类,可以在不加载类的情况下读取到所有类元数据,然后过滤,得到所有满足条件的类的名称

annotation

  • AnnotationAttributes是LinkedHashMap子类,构造方法传入注解,像操作map一样的方便获取注解属性

  • SynthesizedAnnotation标记接口,标记一个注解是被合称的。也就是注解里使用了@AliasFor注解,会为该注解生成动态代理。

  • AnnotationUtils对所有注解都处理了@AliasFor生成代理对象。getXXX方法向上查找一层,findXXX方法向上查找所有层级。synthesizeAnnotation方法为使用了@AliasFor的注解生成代理对象,使用DefaultAnnotationAttributeExtractor提取注解属性,使用SynthesizedAnnotationInvocationHandler生成代理对象。代理对象都实现SynthesizedAnnotation接口。内部大量使用ConcurrentReferenceHashMap。

  • AnnotatedElementUtils被注解元素的工具类

  • OrderUtils获取注解的顺序,支持@Order和@Priority

  • AnnotationAwareOrderComparator继承OrderComparator,先使用实现接口顺序,后使用注解顺序。

  • AliasFor注解,通过AnnotationUtils获取注解才会解析并生成动态代理,用法见JavaDoc

AliasRegistry.java

  • 别名注册器

  • SimpleAliasRegistry使用map管理别名

AttributeAccessor.class

  • 属性访问器

  • AttributeAccessorSupport使用map管理属性

BridgeMethodResolver.class

  • 桥接方法解析器

CollectionFactory.class

  • 根据集合接口创建适当的集合对象

ConfigurableObjectInputStream.class

Constants.class

  • 常量类,封装类中的常量,提供常量名到常量值的映射

Conventions.class

  • 提供获取对象名称的通用方法

DecoratingClassLoader.class

DecoratingProxy.class

ExceptionDepthComparator.class

GenericTypeResolver.class

InfrastructureProxy.class

MethodClassKey.class

MethodIntrospector.class

  • 方法内省器,提供方法过滤和方法元数据查找

MethodParameter.class

  • 封装方法参数,以及泛型层级操作

NamedInheritableThreadLocal.class

NamedThreadLocal.class

OrderComparator.class

  • 顺序比较器

OverridingClassLoader.class ParameterizedTypeReference.class

  • 提供子类泛型解析能力

ParameterNameDiscoverer.class

  • 参数名发现器,提供通过反射和本地变量表获取实现

  • StandardReflectionParameterNameDiscoverer

  • LocalVariableTableParameterNameDiscoverer

  • PrioritizedParameterNameDiscoverer

  • DefaultParameterNameDiscoverer

ResolvableType.class

  • 封装JDK的Type,提供链式导航等

SpringProperties.class

  • spring.properties自动加载,提供属性获取方法

posted @ 2020-04-18 15:16  java拌饭  阅读(299)  评论(0编辑  收藏  举报