日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring注解编程基石(二)

發布時間:2024/4/13 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring注解编程基石(二) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

?

輔助類

AttributeMethods

AnnotationFilter

RepeatableContainers

MergedAnnotation接口

AnnotationsProcessor接口

MergedAnnotationSelector

AnnotationsScanner

AnnotationTypeMapping

MergedAnnotation接口

MergedAnnotations接口

TypeMappedAnnotations


Spring注解編程基石(一)

Spring注解編程基石(二)

Spring注解編程基石(三)???????

Spring注解編程基石(四)???????


輔助類

AttributeMethods

AttributeMethods是對一個注解的屬性方法的封裝類。提供快速方式訪問Annotation的屬性方法,具有緩存功能。

final class AttributeMethods {static final AttributeMethods NONE = new AttributeMethods(null, new Method[0]);private static final Map<Class<? extends Annotation>, AttributeMethods> cache =new ConcurrentReferenceHashMap<>();private static final Comparator<Method> methodComparator = (m1, m2) -> {if (m1 != null && m2 != null) {return m1.getName().compareTo(m2.getName());}return m1 != null ? -1 : 1;};@Nullable//注解類型private final Class<? extends Annotation> annotationType;//注解的屬性方法private final Method[] attributeMethods;//注解方法沒有設置時是否拋出異常private final boolean[] canThrowTypeNotPresentException;//是否有默認值方法private final boolean hasDefaultValueMethod;//是否有嵌套注解private final boolean hasNestedAnnotation;private AttributeMethods(@Nullable Class<? extends Annotation> annotationType, Method[] attributeMethods) {this.annotationType = annotationType;this.attributeMethods = attributeMethods;this.canThrowTypeNotPresentException = new boolean[attributeMethods.length];boolean foundDefaultValueMethod = false;boolean foundNestedAnnotation = false;for (int i = 0; i < attributeMethods.length; i++) {Method method = this.attributeMethods[i];Class<?> type = method.getReturnType();if (method.getDefaultValue() != null) {foundDefaultValueMethod = true;}//如果屬性類型為注解、數組、泛型,則表示為嵌套類型。if (type.isAnnotation() || (type.isArray() && type.getComponentType().isAnnotation())) {foundNestedAnnotation = true;}ReflectionUtils.makeAccessible(method);//如果屬性類型為類、類數組、枚舉,則不賦值時要拋出異常。this.canThrowTypeNotPresentException[i] = (type == Class.class || type == Class[].class || type.isEnum());}this.hasDefaultValueMethod = foundDefaultValueMethod;this.hasNestedAnnotation = foundNestedAnnotation;}//是否僅包含value屬性boolean hasOnlyValueAttribute() {return (this.attributeMethods.length == 1 &&MergedAnnotation.VALUE.equals(this.attributeMethods[0].getName()));}//判斷注解是否合法,如果需要賦值的屬性,沒有賦值則返回false。boolean isValid(Annotation annotation) {assertAnnotation(annotation);for (int i = 0; i < size(); i++) {if (canThrowTypeNotPresentException(i)) {try {get(i).invoke(annotation);}catch (Throwable ex) {return false;}}}return true;}... ... ... ... boolean hasDefaultValueMethod() {return this.hasDefaultValueMethod;}boolean hasNestedAnnotation() {return this.hasNestedAnnotation;}//計算注解類型的屬性方法。static AttributeMethods forAnnotationType(@Nullable Class<? extends Annotation> annotationType) {if (annotationType == null) {return NONE;}return cache.computeIfAbsent(annotationType, AttributeMethods::compute);}//計算注解類型的屬性方法。private static AttributeMethods compute(Class<? extends Annotation> annotationType) {Method[] methods = annotationType.getDeclaredMethods();int size = methods.length;for (int i = 0; i < methods.length; i++) {if (!isAttributeMethod(methods[i])) {methods[i] = null;size--;}}if (size == 0) {return NONE;}Arrays.sort(methods, methodComparator);Method[] attributeMethods = Arrays.copyOf(methods, size);return new AttributeMethods(annotationType, attributeMethods);}//方式是不是屬性方法:沒有形參并且返回值不為void的方法為屬性方法。private static boolean isAttributeMethod(Method method) {return (method.getParameterCount() == 0 && method.getReturnType() != void.class);}}

AnnotationFilter

函數式接口,用于過濾指定Annotation。

?

@FunctionalInterface public interface AnnotationFilter {AnnotationFilter PLAIN = packages("java.lang", "org.springframework.lang");AnnotationFilter JAVA = packages("java", "javax");// 過濾掉所有annotationAnnotationFilter ALL = new AnnotationFilter() {@Overridepublic boolean matches(Annotation annotation) {return true;}@Overridepublic boolean matches(Class<?> type) {return true;}@Overridepublic boolean matches(String typeName) {return true;}@Overridepublic String toString() {return "All annotations filtered";}};// 不過濾任何annotationAnnotationFilter NONE = new AnnotationFilter() {@Overridepublic boolean matches(Annotation annotation) {return false;}@Overridepublic boolean matches(Class<?> type) {return false;}@Overridepublic boolean matches(String typeName) {return false;}@Overridepublic String toString() {return "No annotation filtering";}};default boolean matches(Annotation annotation) {return matches(annotation.annotationType());}default boolean matches(Class<?> type) {return matches(type.getName());}boolean matches(String typeName);static AnnotationFilter packages(String... packages) {return new PackagesAnnotationFilter(packages);}}

PackagesAnnotationFilter

PackagesAnnotationFilter為AnnotationFilter的一個實現類,如果某個Annotation存在某個package下則過濾。

final class PackagesAnnotationFilter implements AnnotationFilter

RepeatableContainers

可重復注解容器。

//可重復注解容器 public abstract class RepeatableContainers {@Nullableprivate final RepeatableContainers parent;private RepeatableContainers(@Nullable RepeatableContainers parent) {this.parent = parent;}//在一個可重復注解和包含注解之間建立關系。public RepeatableContainers and(Class<? extends Annotation> container,Class<? extends Annotation> repeatable) {return new ExplicitRepeatableContainer(this, repeatable, container);}//查找可重復注解。@NullableAnnotation[] findRepeatedAnnotations(Annotation annotation) {if (this.parent == null) {return null;}return this.parent.findRepeatedAnnotations(annotation);}public static RepeatableContainers standardRepeatables() {return StandardRepeatableContainers.INSTANCE;}public static RepeatableContainers of(Class<? extends Annotation> repeatable, @Nullable Class<? extends Annotation> container) {return new ExplicitRepeatableContainer(null, repeatable, container);}public static RepeatableContainers none() {return NoRepeatableContainers.INSTANCE;}}

StandardRepeatableContainers

使用Java @Repeatable查找的標準容器。@Repeatable的用法:

public @interface Repeatable {Class<? extends Annotation> value(); }@interface Persons {Person[]? value(); }@Repeatable(Persons.class) @interface Person{String role default ""; }@Person(role="artist") @Person(role="coder") @Person(role="PM") public class SuperMan{}

上述代碼,@Persons注解,僅有value屬性,值類型為數組,并且元素類型為注解 @Person。 @Person被@Repeatable注解。

private static class StandardRepeatableContainers extends RepeatableContainers {private static final Map<Class<? extends Annotation>, Object> cache = new ConcurrentReferenceHashMap<>();private static final Object NONE = new Object();private static StandardRepeatableContainers INSTANCE = new StandardRepeatableContainers();StandardRepeatableContainers() {super(null);}@Override@NullableAnnotation[] findRepeatedAnnotations(Annotation annotation) {Method method = getRepeatedAnnotationsMethod(annotation.annotationType());if (method != null) {return (Annotation[]) ReflectionUtils.invokeMethod(method, annotation);}return super.findRepeatedAnnotations(annotation);}@Nullableprivate static Method getRepeatedAnnotationsMethod(Class<? extends Annotation> annotationType) {Object result = cache.computeIfAbsent(annotationType,StandardRepeatableContainers::computeRepeatedAnnotationsMethod);return (result != NONE ? (Method) result : null);}//計算可重復注解方法(即屬性)private static Object computeRepeatedAnnotationsMethod(Class<? extends Annotation> annotationType) {AttributeMethods methods = AttributeMethods.forAnnotationType(annotationType);//僅有value屬性if (methods.hasOnlyValueAttribute()) {Method method = methods.get(0);Class<?> returnType = method.getReturnType();//如果屬性值類型為數組,if (returnType.isArray()) {//數組元素類型Class<?> componentType = returnType.getComponentType();//數組元素類型為 Annotation 并且 被 @Repeatable注解if (Annotation.class.isAssignableFrom(componentType) &&componentType.isAnnotationPresent(Repeatable.class)) {return method;}}}return NONE;}}

ExplicitRepeatableContainer

顯示映射的可重復容器。

private static class ExplicitRepeatableContainer extends RepeatableContainers {//可重復的注解private final Class<? extends Annotation> repeatable;//容器注解。private final Class<? extends Annotation> container;//value值方法private final Method valueMethod;ExplicitRepeatableContainer(@Nullable RepeatableContainers parent,Class<? extends Annotation> repeatable, @Nullable Class<? extends Annotation> container) {super(parent);Assert.notNull(repeatable, "Repeatable must not be null");//如果容器為null,則通過 repeatable 注解 獲取if (container == null) {container = deduceContainer(repeatable);}//獲取container的value屬性Method valueMethod = AttributeMethods.forAnnotationType(container).get(MergedAnnotation.VALUE);//驗證try {if (valueMethod == null) {throw new NoSuchMethodException("No value method found");}Class<?> returnType = valueMethod.getReturnType();if (!returnType.isArray() || returnType.getComponentType() != repeatable) {throw new AnnotationConfigurationException("Container type [" +container.getName() +"] must declare a 'value' attribute for an array of type [" +repeatable.getName() + "]");}}catch (AnnotationConfigurationException ex) {throw ex;}catch (Throwable ex) {throw new AnnotationConfigurationException("Invalid declaration of container type [" + container.getName() +"] for repeatable annotation [" + repeatable.getName() + "]",ex);}this.repeatable = repeatable;this.container = container;this.valueMethod = valueMethod;}//推算containerprivate Class<? extends Annotation> deduceContainer(Class<? extends Annotation> repeatable) {//獲取注解的 @Repeatable 實例Repeatable annotation = repeatable.getAnnotation(Repeatable.class);Assert.notNull(annotation, () -> "Annotation type must be a repeatable annotation: " +"failed to resolve container type for " + repeatable.getName());//獲取實例的value屬性,獲取到container注解類型return annotation.value();}@Override@NullableAnnotation[] findRepeatedAnnotations(Annotation annotation) {if (this.container.isAssignableFrom(annotation.annotationType())) {return (Annotation[]) ReflectionUtils.invokeMethod(this.valueMethod, annotation);}return super.findRepeatedAnnotations(annotation);}}

NoRepeatableContainers

?

MergedAnnotation接口

MergedAnnotation接口用于封裝來源于多個不同的注解的屬性。

public interface MergedAnnotation<A extends Annotation> {//屬性名稱String VALUE = "value";//返回annotation類型Class<A> getType();//是否應用boolean isPresent();//是否直接應用boolean isDirectlyPresent();//是否元注解應用boolean isMetaPresent();//返回注解的距離。-1:沒有應用,0:直接應用,1:元注解,2:元注解的元注解。int getDistance();int getAggregateIndex();@NullableObject getSource();@NullableMergedAnnotation<?> getMetaSource();MergedAnnotation<?> getRoot();List<Class<? extends Annotation>> getMetaTypes();boolean hasNonDefaultValue(String attributeName);boolean hasDefaultValue(String attributeName) throws NoSuchElementException;Optional<Object> getValue(String attributeName);<T> Optional<T> getValue(String attributeName, Class<T> type);...... ... ... ... }

還包括返回指定類型的屬性值

byte getByte(String attributeName) throws NoSuchElementException;byte[] getByteArray(String attributeName) throws NoSuchElementException;boolean getBoolean(String attributeName) throws NoSuchElementException;boolean[] getBooleanArray(String attributeName) throws NoSuchElementException;char getChar(String attributeName) throws NoSuchElementException;char[] getCharArray(String attributeName) throws NoSuchElementException;short getShort(String attributeName) throws NoSuchElementException;short[] getShortArray(String attributeName) throws NoSuchElementException;int getInt(String attributeName) throws NoSuchElementException;int[] getIntArray(String attributeName) throws NoSuchElementException;long getLong(String attributeName) throws NoSuchElementException;long[] getLongArray(String attributeName) throws NoSuchElementException;double getDouble(String attributeName) throws NoSuchElementException;double[] getDoubleArray(String attributeName) throws NoSuchElementException;float getFloat(String attributeName) throws NoSuchElementException;float[] getFloatArray(String attributeName) throws NoSuchElementException;String getString(String attributeName) throws NoSuchElementException;String[] getStringArray(String attributeName) throws NoSuchElementException;Class<?> getClass(String attributeName) throws NoSuchElementException;Class<?>[] getClassArray(String attributeName) throws NoSuchElementException;<E extends Enum<E>> E getEnum(String attributeName, Class<E> type) throws NoSuchElementException;<E extends Enum<E>> E[] getEnumArray(String attributeName, Class<E> type) throws NoSuchElementException;<T extends Annotation> MergedAnnotation<T> getAnnotation(String attributeName, Class<T> type)throws NoSuchElementException;<T extends Annotation> MergedAnnotation<T>[] getAnnotationArray(String attributeName, Class<T> type)throws NoSuchElementException;

?構造實例的靜態方法

static <A extends Annotation> MergedAnnotation<A> from(A annotation) {return from(null, annotation);}static <A extends Annotation> MergedAnnotation<A> from(@Nullable Object source, A annotation) {return TypeMappedAnnotation.from(source, annotation);}static <A extends Annotation> MergedAnnotation<A> of(Class<A> annotationType) {return of(null, annotationType, null);}static <A extends Annotation> MergedAnnotation<A> of(Class<A> annotationType, @Nullable Map<String, ?> attributes) {return of(null, annotationType, attributes);}static <A extends Annotation> MergedAnnotation<A> of(@Nullable AnnotatedElement source, Class<A> annotationType, @Nullable Map<String, ?> attributes) {return of(null, source, annotationType, attributes);}static <A extends Annotation> MergedAnnotation<A> of(@Nullable ClassLoader classLoader, @Nullable Object source,Class<A> annotationType, @Nullable Map<String, ?> attributes) {return TypeMappedAnnotation.of(classLoader, source, annotationType, attributes);}

AnnotationsProcessor接口

?

//用于處理 annotations的 回調 函數式接口 @FunctionalInterface interface AnnotationsProcessor<C, R> {@Nullabledefault R doWithAggregate(C context, int aggregateIndex) {return null;}@NullableR doWithAnnotations(C context, int aggregateIndex, @Nullable Object source, Annotation[] annotations);@Nullabledefault R finish(@Nullable R result) {return result;}}

IsPresent

private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {private static final IsPresent[] SHARED;static {SHARED = new IsPresent[4];SHARED[0] = new IsPresent(RepeatableContainers.none(), AnnotationFilter.PLAIN, true);SHARED[1] = new IsPresent(RepeatableContainers.none(), AnnotationFilter.PLAIN, false); //用于@repeatable注解SHARED[2] = new IsPresent(RepeatableContainers.standardRepeatables(), AnnotationFilter.PLAIN, true);SHARED[3] = new IsPresent(RepeatableContainers.standardRepeatables(), AnnotationFilter.PLAIN, false);}static IsPresent get(RepeatableContainers repeatableContainers,AnnotationFilter annotationFilter, boolean directOnly) {// Use a single shared instance for common combinationsif (annotationFilter == AnnotationFilter.PLAIN) {if (repeatableContainers == RepeatableContainers.none()) {return SHARED[directOnly ? 0 : 1];}if (repeatableContainers == RepeatableContainers.standardRepeatables()) {return SHARED[directOnly ? 2 : 3];}}return new IsPresent(repeatableContainers, annotationFilter, directOnly);}}

?

public Boolean doWithAnnotations(Object requiredType, int aggregateIndex,@Nullable Object source, Annotation[] annotations) {for (Annotation annotation : annotations) {if (annotation != null) {Class<? extends Annotation> type = annotation.annotationType();if (type != null && !this.annotationFilter.matches(type)) {//如果注解集合包含requiredTypeif (type == requiredType || type.getName().equals(requiredType)) {return Boolean.TRUE;}//獲取可重復注解實例。Annotation[] repeatedAnnotations =this.repeatableContainers.findRepeatedAnnotations(annotation);if (repeatedAnnotations != null) {Boolean result = doWithAnnotations(requiredType, aggregateIndex, source, repeatedAnnotations);if (result != null) {return result;}}if (!this.directOnly) {AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(type);for (int i = 0; i < mappings.size(); i++) {AnnotationTypeMapping mapping = mappings.get(i);if (isMappingForType(mapping, this.annotationFilter, requiredType)) {return Boolean.TRUE;}}}}}}return null;}

AggregatesCollector

private class AggregatesCollector implements AnnotationsProcessor<Object, List<Aggregate>> {private final List<Aggregate> aggregates = new ArrayList<>();@Override@Nullablepublic List<Aggregate> doWithAnnotations(Object criteria, int aggregateIndex,@Nullable Object source, Annotation[] annotations) {//把注解加入集合this.aggregates.add(createAggregate(aggregateIndex, source, annotations));return null;}private Aggregate createAggregate(int aggregateIndex, @Nullable Object source, Annotation[] annotations) {List<Annotation> aggregateAnnotations = getAggregateAnnotations(annotations);return new Aggregate(aggregateIndex, source, aggregateAnnotations);}private List<Annotation> getAggregateAnnotations(Annotation[] annotations) {List<Annotation> result = new ArrayList<>(annotations.length);addAggregateAnnotations(result, annotations);return result;}private void addAggregateAnnotations(List<Annotation> aggregateAnnotations, Annotation[] annotations) {for (Annotation annotation : annotations) {if (annotation != null && !annotationFilter.matches(annotation)) {Annotation[] repeatedAnnotations = repeatableContainers.findRepeatedAnnotations(annotation);if (repeatedAnnotations != null) {addAggregateAnnotations(aggregateAnnotations, repeatedAnnotations);}else {aggregateAnnotations.add(annotation);}}}}@Overridepublic List<Aggregate> finish(@Nullable List<Aggregate> processResult) {return this.aggregates;}}

MergedAnnotationFinder

//找到一個MergedAnnotationprivate class MergedAnnotationFinder<A extends Annotation>implements AnnotationsProcessor<Object, MergedAnnotation<A>> {private final Object requiredType;@Nullableprivate final Predicate<? super MergedAnnotation<A>> predicate;private final MergedAnnotationSelector<A> selector;@Nullableprivate MergedAnnotation<A> result;MergedAnnotationFinder(Object requiredType, @Nullable Predicate<? super MergedAnnotation<A>> predicate,@Nullable MergedAnnotationSelector<A> selector) {this.requiredType = requiredType;this.predicate = predicate;this.selector = (selector != null ? selector : MergedAnnotationSelectors.nearest());}@Override@Nullablepublic MergedAnnotation<A> doWithAggregate(Object context, int aggregateIndex) {return this.result;}@Override@Nullablepublic MergedAnnotation<A> doWithAnnotations(Object type, int aggregateIndex,@Nullable Object source, Annotation[] annotations) {for (Annotation annotation : annotations) {if (annotation != null && !annotationFilter.matches(annotation)) {MergedAnnotation<A> result = process(type, aggregateIndex, source, annotation);if (result != null) {return result;}}}return null;}@Nullableprivate MergedAnnotation<A> process(Object type, int aggregateIndex, @Nullable Object source, Annotation annotation) {//找到可重復注解實例。Annotation[] repeatedAnnotations = repeatableContainers.findRepeatedAnnotations(annotation);if (repeatedAnnotations != null) {//找到第一個return doWithAnnotations(type, aggregateIndex, source, repeatedAnnotations);}//如果不是可重復注解,則獲取注解類型映射AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(annotation.annotationType(), annotationFilter);for (int i = 0; i < mappings.size(); i++) {AnnotationTypeMapping mapping = mappings.get(i);if (isMappingForType(mapping, annotationFilter, this.requiredType)) {MergedAnnotation<A> candidate = TypeMappedAnnotation.createIfPossible(mapping, source, annotation, aggregateIndex, IntrospectionFailureLogger.INFO);if (candidate != null && (this.predicate == null || this.predicate.test(candidate))) {//是最合適的,則返回if (this.selector.isBestCandidate(candidate)) {return candidate;}//否則更新候選者(與上一次選擇的進行比較,保留較合適的。)。updateLastResult(candidate);}}}return null;}//與上一次選擇的進行比較,保留較合適的。private void updateLastResult(MergedAnnotation<A> candidate) {MergedAnnotation<A> lastResult = this.result;this.result = (lastResult != null ? this.selector.select(lastResult, candidate) : candidate);}@Override@Nullablepublic MergedAnnotation<A> finish(@Nullable MergedAnnotation<A> result) {return (result != null ? result : this.result);}}

MergedAnnotationSelector

AnnotationsScanner

?

AnnotationTypeMapping

?

MergedAnnotation接口

MergedAnnotation接口用于描述一個注解屬性合并了的注解。

構造實例

static <A extends Annotation> MergedAnnotation<A> missing() {return MissingMergedAnnotation.getInstance();}static <A extends Annotation> MergedAnnotation<A> from(A annotation) {return from(null, annotation);}static <A extends Annotation> MergedAnnotation<A> from(@Nullable Object source, A annotation) {return TypeMappedAnnotation.from(source, annotation);}static <A extends Annotation> MergedAnnotation<A> of(Class<A> annotationType) {return of(null, annotationType, null);}static <A extends Annotation> MergedAnnotation<A> of(Class<A> annotationType, @Nullable Map<String, ?> attributes) {return of(null, annotationType, attributes);}static <A extends Annotation> MergedAnnotation<A> of(@Nullable AnnotatedElement source, Class<A> annotationType, @Nullable Map<String, ?> attributes) {return of(null, source, annotationType, attributes);}static <A extends Annotation> MergedAnnotation<A> of(@Nullable ClassLoader classLoader, @Nullable Object source,Class<A> annotationType, @Nullable Map<String, ?> attributes) {return TypeMappedAnnotation.of(classLoader, source, annotationType, attributes);}

判斷方法

public interface MergedAnnotation<A extends Annotation> {String VALUE = "value";Class<A> getType();boolean isPresent();boolean isDirectlyPresent();boolean isMetaPresent();int getDistance();int getAggregateIndex();@NullableObject getSource();@NullableMergedAnnotation<?> getMetaSource();MergedAnnotation<?> getRoot();List<Class<? extends Annotation>> getMetaTypes();boolean hasNonDefaultValue(String attributeName);boolean hasDefaultValue(String attributeName) throws NoSuchElementException; }

獲取屬性值

* get***(String attributeName) throws NoSuchElementException;

AbstractMergedAnnotation

abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {@Nullableprivate volatile A synthesizedAnnotation;@Override//是否直接注解(getDistance == 0)public boolean isDirectlyPresent() {return isPresent() && getDistance() == 0;}@Override//是否元注解注解(getDistance > 0)public boolean isMetaPresent() {return isPresent() && getDistance() > 0;}@Overridepublic boolean hasNonDefaultValue(String attributeName) {return !hasDefaultValue(attributeName);}@Overridepublic * get***(String attributeName);... ... ... //所有獲取屬性值方法,實際訪問此方法。private <T> T getRequiredAttributeValue(String attributeName, Class<T> type) {T value = getAttributeValue(attributeName, type);if (value == null) {throw new NoSuchElementException("No attribute named '" + attributeName +"' present in merged annotation " + getType().getName());}return value;}@Overridepublic MergedAnnotation<A> filterDefaultValues() {return filterAttributes(this::hasNonDefaultValue);}@Overridepublic AnnotationAttributes asAnnotationAttributes(Adapt... adaptations) {return asMap(mergedAnnotation -> new AnnotationAttributes(mergedAnnotation.getType()), adaptations);}@Overridepublic Optional<A> synthesize(Predicate<? super MergedAnnotation<A>> condition)throws NoSuchElementException {return (condition.test(this) ? Optional.of(synthesize()) : Optional.empty());}@Override//屬性合成(僅合成應用了的注解屬性)。public A synthesize() {if (!isPresent()) {throw new NoSuchElementException("Unable to synthesize missing annotation");}A synthesized = this.synthesizedAnnotation;if (synthesized == null) {synthesized = createSynthesized();this.synthesizedAnnotation = synthesized;}return synthesized;}@Nullableprotected abstract <T> T getAttributeValue(String attributeName, Class<T> type);/*** Factory method used to create the synthesized annotation.*/protected abstract A createSynthesized();}

MissingMergedAnnotation

空合成注解

TypeMappedAnnotation

?

MergedAnnotations接口

?MergedAnnotations用于提供訪問MergedAnnotation集合的方法。

public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {//使用應用注解(直接注解或元注解)<A extends Annotation> boolean isPresent(Class<A> annotationType); boolean isPresent(String annotationType);//使用直接應用注解<A extends Annotation> boolean isDirectlyPresent(Class<A> annotationType);boolean isDirectlyPresent(String annotationType);//獲取離得最近的注解(直接注解或元注解)<A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType);//獲取離得最近的注解(直接注解或元注解)<A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,@Nullable Predicate<? super MergedAnnotation<A>> predicate);//獲取通過selector 選擇合適的注解(直接注解或元注解)<A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,@Nullable Predicate<? super MergedAnnotation<A>> predicate,@Nullable MergedAnnotationSelector<A> selector);<A extends Annotation> MergedAnnotation<A> get(String annotationType);<A extends Annotation> MergedAnnotation<A> get(String annotationType,@Nullable Predicate<? super MergedAnnotation<A>> predicate);<A extends Annotation> MergedAnnotation<A> get(String annotationType,@Nullable Predicate<? super MergedAnnotation<A>> predicate,@Nullable MergedAnnotationSelector<A> selector);static MergedAnnotations from(AnnotatedElement element) {return from(element, SearchStrategy.DIRECT);}static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy) {return from(element, searchStrategy, RepeatableContainers.standardRepeatables());}static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,RepeatableContainers repeatableContainers) {return TypeMappedAnnotations.from(element, searchStrategy, repeatableContainers, AnnotationFilter.PLAIN);}static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {return TypeMappedAnnotations.from(element, searchStrategy, repeatableContainers, annotationFilter);}static MergedAnnotations from(Annotation... annotations) {return from(annotations, annotations);}static MergedAnnotations from(Object source, Annotation... annotations) {return from(source, annotations, RepeatableContainers.standardRepeatables());}static MergedAnnotations from(Object source, Annotation[] annotations, RepeatableContainers repeatableContainers) {return TypeMappedAnnotations.from(source, annotations, repeatableContainers, AnnotationFilter.PLAIN);}static MergedAnnotations from(Object source, Annotation[] annotations,RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {return TypeMappedAnnotations.from(source, annotations, repeatableContainers, annotationFilter);}static MergedAnnotations of(Collection<MergedAnnotation<?>> annotations) {return MergedAnnotationsCollection.of(annotations);}}

查找策略

enum SearchStrategy {//僅查找直接注解,不考慮@Inherited,超類或者接口。DIRECT,//查找所有直接注解,或者superclass應用@Inherited了的注解。僅適用于Class。其他AnnotatedElement 不適用。INHERITED_ANNOTATIONS,//查找所有直接注解,或者超類的注解,與INHERITED_ANNOTATIONS相似,但是元注解不需要應用@InheritedSUPERCLASS,//包含superclass,接口,注解不需要應用@InheritedTYPE_HIERARCHY,//類似TYPE_HIERARCHY,同時又查找內部內TYPE_HIERARCHY_AND_ENCLOSING_CLASSES}

?

TypeMappedAnnotations

TypeMappedAnnotations為MergedAnnotations的一個實現。

構造實例

static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {if (AnnotationsScanner.isKnownEmpty(element, searchStrategy)) {return NONE;}return new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter);}static MergedAnnotations from(@Nullable Object source, Annotation[] annotations,RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {if (annotations.length == 0) {return NONE;}return new TypeMappedAnnotations(source, annotations, repeatableContainers, annotationFilter);}

屬性

final class TypeMappedAnnotations implements MergedAnnotations {//沒有注解時使用的實例static final MergedAnnotations NONE = new TypeMappedAnnotations(null, new Annotation[0], RepeatableContainers.none(), AnnotationFilter.ALL);@Nullableprivate final Object source;@Nullable//可注解元素實例private final AnnotatedElement element;@Nullable//查找策略private final SearchStrategy searchStrategy;@Nullable//注解private final Annotation[] annotations;//可重復注解containerprivate final RepeatableContainers repeatableContainers;//注解過濾private final AnnotationFilter annotationFilter;@Nullable//private volatile List<Aggregate> aggregates;}

?判斷是否應用注解方法

@Overridepublic <A extends Annotation> boolean isPresent(Class<A> annotationType) {//過濾直接返回false。if (this.annotationFilter.matches(annotationType)) {return false;}return Boolean.TRUE.equals(scan(annotationType,IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));}@Overridepublic boolean isPresent(String annotationType) {if (this.annotationFilter.matches(annotationType)) {return false;}return Boolean.TRUE.equals(scan(annotationType,IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));}@Overridepublic <A extends Annotation> boolean isDirectlyPresent(Class<A> annotationType) {if (this.annotationFilter.matches(annotationType)) {return false;}return Boolean.TRUE.equals(scan(annotationType,IsPresent.get(this.repeatableContainers, this.annotationFilter, true)));}@Overridepublic boolean isDirectlyPresent(String annotationType) {if (this.annotationFilter.matches(annotationType)) {return false;}return Boolean.TRUE.equals(scan(annotationType,IsPresent.get(this.repeatableContainers, this.annotationFilter, true)));}

獲取MergedAnnotation方法

//查找MergedAnnotationpublic <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,@Nullable Predicate<? super MergedAnnotation<A>> predicate,@Nullable MergedAnnotationSelector<A> selector) {if (this.annotationFilter.matches(annotationType)) {return MergedAnnotation.missing();}MergedAnnotation<A> result = scan(annotationType,new MergedAnnotationFinder<>(annotationType, predicate, selector));return (result != null ? result : MergedAnnotation.missing());}@Overridepublic <A extends Annotation> MergedAnnotation<A> get(String annotationType) {return get(annotationType, null, null);}@Overridepublic <A extends Annotation> MergedAnnotation<A> get(String annotationType,@Nullable Predicate<? super MergedAnnotation<A>> predicate) {return get(annotationType, predicate, null);}@Overridepublic <A extends Annotation> MergedAnnotation<A> get(String annotationType,@Nullable Predicate<? super MergedAnnotation<A>> predicate,@Nullable MergedAnnotationSelector<A> selector) {if (this.annotationFilter.matches(annotationType)) {return MergedAnnotation.missing();}MergedAnnotation<A> result = scan(annotationType,new MergedAnnotationFinder<>(annotationType, predicate, selector));return (result != null ? result : MergedAnnotation.missing());}

?

總結

以上是生活随笔為你收集整理的Spring注解编程基石(二)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。