|
| 1 | +/* |
| 2 | + * Copyright 2002-2024 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.context.aot; |
| 18 | + |
| 19 | +import java.util.Arrays; |
| 20 | +import java.util.HashSet; |
| 21 | +import java.util.LinkedHashSet; |
| 22 | +import java.util.Set; |
| 23 | +import java.util.stream.StreamSupport; |
| 24 | + |
| 25 | +import org.springframework.aot.generate.GenerationContext; |
| 26 | +import org.springframework.aot.hint.RuntimeHints; |
| 27 | +import org.springframework.aot.hint.annotation.Reflective; |
| 28 | +import org.springframework.aot.hint.annotation.ReflectiveProcessor; |
| 29 | +import org.springframework.aot.hint.annotation.ReflectiveRuntimeHintsRegistrar; |
| 30 | +import org.springframework.aot.hint.annotation.RegisterReflection; |
| 31 | +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; |
| 32 | +import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution; |
| 33 | +import org.springframework.beans.factory.aot.BeanFactoryInitializationCode; |
| 34 | +import org.springframework.beans.factory.config.BeanDefinition; |
| 35 | +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; |
| 36 | +import org.springframework.lang.Nullable; |
| 37 | +import org.springframework.util.ClassUtils; |
| 38 | + |
| 39 | +/** |
| 40 | + * Builder for an {@linkplain BeanFactoryInitializationAotContribution AOT |
| 41 | + * contribution} that detects the presence of {@link Reflective @Reflective} on |
| 42 | + * annotated elements and invoke the underlying {@link ReflectiveProcessor} |
| 43 | + * implementations. |
| 44 | + * |
| 45 | + * <p>Candidates can be provided explicitly or by scanning the classpath. |
| 46 | + * |
| 47 | + * @author Stephane Nicoll |
| 48 | + * @since 6.2 |
| 49 | + * @see Reflective |
| 50 | + * @see RegisterReflection |
| 51 | + */ |
| 52 | +public class ReflectiveProcessorAotContributionBuilder { |
| 53 | + |
| 54 | + private static final ReflectiveRuntimeHintsRegistrar registrar = new ReflectiveRuntimeHintsRegistrar(); |
| 55 | + |
| 56 | + private final Set<Class<?>> classes = new LinkedHashSet<>(); |
| 57 | + |
| 58 | + |
| 59 | + /** |
| 60 | + * Process the given classes by checking the ones that use {@link Reflective}. |
| 61 | + * <p>A class is candidate if it uses {@link Reflective} directly or via a |
| 62 | + * meta-annotation. Type, fields, constructors, methods and enclosed types |
| 63 | + * are inspected. |
| 64 | + * @param classes the classes to inspect |
| 65 | + */ |
| 66 | + public ReflectiveProcessorAotContributionBuilder withClasses(Iterable<Class<?>> classes) { |
| 67 | + this.classes.addAll(StreamSupport.stream(classes.spliterator(), false) |
| 68 | + .filter(registrar::isCandidate).toList()); |
| 69 | + return this; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Process the given classes by checking the ones that use {@link Reflective}. |
| 74 | + * <p>A class is candidate if it uses {@link Reflective} directly or via a |
| 75 | + * meta-annotation. Type, fields, constructors, methods and enclosed types |
| 76 | + * are inspected. |
| 77 | + * @param classes the classes to inspect |
| 78 | + */ |
| 79 | + public ReflectiveProcessorAotContributionBuilder withClasses(Class<?>[] classes) { |
| 80 | + return withClasses(Arrays.asList(classes)); |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Scan the given {@code packageNames} and their sub-packages for classes |
| 85 | + * that uses {@link Reflective}. |
| 86 | + * <p>This performs a "deep scan" by loading every class in the specified |
| 87 | + * packages and search for {@link Reflective} on types, constructors, methods, |
| 88 | + * and fields. Enclosed classes are candidates as well. Classes that fail to |
| 89 | + * load are ignored. |
| 90 | + * @param classLoader the classloader to use |
| 91 | + * @param packageNames the package names to scan |
| 92 | + */ |
| 93 | + public ReflectiveProcessorAotContributionBuilder scan(@Nullable ClassLoader classLoader, String... packageNames) { |
| 94 | + ReflectiveClassPathScanner scanner = new ReflectiveClassPathScanner(classLoader); |
| 95 | + return withClasses(scanner.scan(packageNames)); |
| 96 | + } |
| 97 | + |
| 98 | + @Nullable |
| 99 | + public BeanFactoryInitializationAotContribution build() { |
| 100 | + return (!this.classes.isEmpty() ? new AotContribution(this.classes) : null); |
| 101 | + } |
| 102 | + |
| 103 | + private static class AotContribution implements BeanFactoryInitializationAotContribution { |
| 104 | + |
| 105 | + private final Class<?>[] classes; |
| 106 | + |
| 107 | + public AotContribution(Set<Class<?>> classes) { |
| 108 | + this.classes = classes.toArray(Class<?>[]::new); |
| 109 | + } |
| 110 | + |
| 111 | + @Override |
| 112 | + public void applyTo(GenerationContext generationContext, BeanFactoryInitializationCode beanFactoryInitializationCode) { |
| 113 | + RuntimeHints runtimeHints = generationContext.getRuntimeHints(); |
| 114 | + registrar.registerRuntimeHints(runtimeHints, this.classes); |
| 115 | + } |
| 116 | + |
| 117 | + } |
| 118 | + |
| 119 | + private static class ReflectiveClassPathScanner extends ClassPathScanningCandidateComponentProvider { |
| 120 | + |
| 121 | + @Nullable |
| 122 | + private final ClassLoader classLoader; |
| 123 | + |
| 124 | + ReflectiveClassPathScanner(@Nullable ClassLoader classLoader) { |
| 125 | + super(false); |
| 126 | + this.classLoader = classLoader; |
| 127 | + addIncludeFilter((metadataReader, metadataReaderFactory) -> true); |
| 128 | + } |
| 129 | + |
| 130 | + Class<?>[] scan(String... packageNames) { |
| 131 | + if (logger.isDebugEnabled()) { |
| 132 | + logger.debug("Scanning all types for reflective usage from " + Arrays.toString(packageNames)); |
| 133 | + } |
| 134 | + Set<BeanDefinition> candidates = new HashSet<>(); |
| 135 | + for (String packageName : packageNames) { |
| 136 | + candidates.addAll(findCandidateComponents(packageName)); |
| 137 | + } |
| 138 | + return candidates.stream().map(c -> (Class<?>) c.getAttribute("type")).toArray(Class<?>[]::new); |
| 139 | + } |
| 140 | + |
| 141 | + @Override |
| 142 | + protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { |
| 143 | + String className = beanDefinition.getBeanClassName(); |
| 144 | + if (className != null) { |
| 145 | + try { |
| 146 | + Class<?> type = ClassUtils.forName(className, this.classLoader); |
| 147 | + beanDefinition.setAttribute("type", type); |
| 148 | + return registrar.isCandidate(type); |
| 149 | + } |
| 150 | + catch (Exception ex) { |
| 151 | + if (logger.isTraceEnabled()) { |
| 152 | + logger.trace("Ignoring '%s' for reflective usage: %s".formatted(className, ex.getMessage())); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + return false; |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | +} |
0 commit comments