Add native image runtime hints.

We provide an initial set of runtime hints required to spin up data repositories on GraalVM native image.
Additionally we skip synthetic types during type inspection.

Original Pull Request: #2624
This commit is contained in:
Christoph Strobl
2022-06-07 14:33:39 +02:00
parent d8118de90f
commit 0262380d29
14 changed files with 220 additions and 62 deletions

View File

@@ -0,0 +1,105 @@
/*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.aot;
import java.util.Arrays;
import java.util.Properties;
import org.springframework.aop.SpringProxy;
import org.springframework.aop.framework.Advised;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.DecoratingProxy;
import org.springframework.core.io.InputStreamSource;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.data.repository.core.support.RepositoryFragment;
import org.springframework.data.repository.core.support.RepositoryFragmentsFactoryBean;
import org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport;
import org.springframework.data.repository.query.QueryByExampleExecutor;
import org.springframework.lang.Nullable;
/**
* @author Christoph Strobl
* @since 3.0
*/
public class DataRuntimeHints implements RuntimeHintsRegistrar {
/*
NativeHint(trigger = MappingContext.class,
types = {
@TypeHint(types = {
RepositoryFactoryBeanSupport.class,
RepositoryFragmentsFactoryBean.class,
RepositoryFragment.class,
TransactionalRepositoryFactoryBeanSupport.class,
QueryByExampleExecutor.class,
MappingContext.class,
RepositoryMetadata.class,
RepositoryMetadata.class,
}),
@TypeHint(types = {ReadingConverter.class, WritingConverter.class}),
@TypeHint(types = {Properties.class, BeanFactory.class, InputStreamSource[].class}),
@TypeHint(types = Throwable.class, access = { TypeAccess.DECLARED_CONSTRUCTORS, TypeAccess.DECLARED_FIELDS}),
@TypeHint(typeNames = {
"org.springframework.data.projection.SpelEvaluatingMethodInterceptor$TargetWrapper",
}, access = { TypeAccess.DECLARED_CONSTRUCTORS, TypeAccess.DECLARED_METHODS, TypeAccess.PUBLIC_METHODS })
},
jdkProxies = @JdkProxyHint(typeNames = {
"org.springframework.data.annotation.QueryAnnotation",
"org.springframework.core.annotation.SynthesizedAnnotation" }
),
initialization = @InitializationHint(types = AbstractMappingContext.class, initTime = InitializationTime.BUILD)
)
*/
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
System.out.println("Spring data Runtime Hints");
hints.reflection()
.registerTypes(Arrays.asList(TypeReference.of(RepositoryFactoryBeanSupport.class),
TypeReference.of(RepositoryFragmentsFactoryBean.class), TypeReference.of(RepositoryFragment.class),
TypeReference.of(TransactionalRepositoryFactoryBeanSupport.class),
TypeReference.of(QueryByExampleExecutor.class), TypeReference.of(MappingContext.class),
TypeReference.of(RepositoryMetadata.class)), builder -> {
builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS);
});
hints.reflection().registerTypes(
Arrays.asList(TypeReference.of(Properties.class), TypeReference.of(BeanFactory.class),
TypeReference.of(InputStreamSource[].class)),
builder -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
hints.reflection().registerType(Throwable.class,
builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS));
hints.reflection().registerType(
TypeReference.of("org.springframework.data.projection.SpelEvaluatingMethodInterceptor$TargetWrapper"),
builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.INVOKE_PUBLIC_METHODS));
hints.proxies().registerJdkProxy(TypeReference.of("org.springframework.data.annotation.QueryAnnotation"),
TypeReference.of("org.springframework.core.annotation.SynthesizedAnnotation"));
hints.proxies().registerJdkProxy(TypeReference.of(AuditorAware.class), TypeReference.of(SpringProxy.class), TypeReference.of(Advised.class), TypeReference.of(DecoratingProxy.class));
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.aot;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.ReflectionHints;
import org.springframework.aot.hint.annotation.SimpleReflectiveProcessor;
/**
* @author Christoph Strobl
*/
public class PublicMethodReflectiveProcessor extends SimpleReflectiveProcessor {
@Override
protected void registerTypeHint(ReflectionHints hints, Class<?> type) {
System.out.println("invoking reflective hint annotation for : " + type);
hints.registerType(type, builder -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
}
}

View File

@@ -286,7 +286,7 @@ public class RepositoryRegistrationAotContribution implements BeanRegistrationAo
.registerType(repositoryInformation.getRepositoryBaseClass(), hint ->
hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS))
.registerType(repositoryInformation.getDomainType(), hint ->
hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS));
hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS));
// Repository Fragments
for (RepositoryFragment<?> fragment : getRepositoryInformation().getFragments()) {
@@ -308,7 +308,7 @@ public class RepositoryRegistrationAotContribution implements BeanRegistrationAo
SpringProxy.class, Advised.class, DecoratingProxy.class);
// Transactional Repository Proxy
repositoryContext.ifTransactionManagerPresent(transactionManagerBeanNames -> {
//repositoryContext.ifTransactionManagerPresent(transactionManagerBeanNames -> {
// TODO: Is the following double JDK Proxy registration above necessary or would a single JDK Proxy
// registration suffice?
@@ -327,7 +327,7 @@ public class RepositoryRegistrationAotContribution implements BeanRegistrationAo
contribution.getRuntimeHints().proxies()
.registerJdkProxy(transactionalRepositoryProxyTypeReferences.toArray(new TypeReference[0]));
}
});
//});
// Reactive Repositories
if (repositoryInformation.isReactiveRepository()) {
@@ -396,39 +396,25 @@ public class RepositoryRegistrationAotContribution implements BeanRegistrationAo
.registerJdkProxy(type, TargetAware.class, SpringProxy.class, DecoratingProxy.class);
}
protected void contribute(AotRepositoryContext repositoryContext, GenerationContext generationContext) {
repositoryContext.getResolvedTypes().stream()
.filter(it -> !isJavaOrPrimitiveType(it))
.forEach(it -> contributeType(it, generationContext));
repositoryContext.getResolvedAnnotations().stream()
.filter(this::isSpringDataManagedAnnotation)
.map(MergedAnnotation::getType)
.forEach(it -> contributeType(it, generationContext));
}
private boolean isJavaOrPrimitiveType(Class<?> type) {
static boolean isJavaOrPrimitiveType(Class<?> type) {
return TypeUtils.type(type).isPartOf("java")
|| type.isPrimitive()
|| ClassUtils.isPrimitiveArray(type);
}
private boolean isSpringDataManagedAnnotation(MergedAnnotation<?> annotation) {
static boolean isSpringDataManagedAnnotation(MergedAnnotation<?> annotation) {
return annotation != null
&& (isInSpringDataNamespace(annotation.getType()) || annotation.getMetaTypes().stream()
.anyMatch(this::isInSpringDataNamespace));
.anyMatch(RepositoryRegistrationAotContribution::isInSpringDataNamespace));
}
private boolean isInSpringDataNamespace(Class<?> type) {
static boolean isInSpringDataNamespace(Class<?> type) {
return type != null && type.getPackage().getName().startsWith(TypeContributor.DATA_NAMESPACE);
}
protected void contributeType(Class<?> type, GenerationContext generationContext) {
logTrace("Contributing type information for [%s]", type);
static void contributeType(Class<?> type, GenerationContext generationContext) {
TypeContributor.contribute(type, it -> true, generationContext);
}

View File

@@ -34,6 +34,7 @@ import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
import org.springframework.data.repository.config.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
@@ -51,7 +52,7 @@ import org.springframework.util.StringUtils;
* via the {@link FactoryBean#OBJECT_TYPE_ATTRIBUTE}.
* </p>
* <p>
* With {@link RepositoryRegistrationAotContribution#contribute(AotRepositoryContext, GenerationContext)}, stores
* With {@link RepositoryRegistrationAotProcessor#contribute(AotRepositoryContext, GenerationContext)}, stores
* can provide custom logic for contributing additional (eg. reflection) configuration. By default, reflection
* configuration will be added for types reachable from the repository declaration and query methods as well as
* all used {@link Annotation annotations} from the {@literal org.springframework.data} namespace.
@@ -83,6 +84,19 @@ public class RepositoryRegistrationAotProcessor implements BeanRegistrationAotPr
: null;
}
protected void contribute(AotRepositoryContext repositoryContext, GenerationContext generationContext) {
repositoryContext.getResolvedTypes().stream()
.filter(it -> !RepositoryRegistrationAotContribution
.isJavaOrPrimitiveType(it))
.forEach(it -> RepositoryRegistrationAotContribution.contributeType(it, generationContext));
repositoryContext.getResolvedAnnotations().stream()
.filter(RepositoryRegistrationAotContribution::isSpringDataManagedAnnotation)
.map(MergedAnnotation::getType)
.forEach(it -> RepositoryRegistrationAotContribution.contributeType(it, generationContext));
}
private boolean isRepositoryBean(RegisteredBean bean) {
return bean != null && getConfigMap().containsKey(bean.getBeanName());
}
@@ -93,7 +107,7 @@ public class RepositoryRegistrationAotProcessor implements BeanRegistrationAotPr
RepositoryRegistrationAotContribution contribution =
RepositoryRegistrationAotContribution.fromProcessor(this).forBean(repositoryBean);
return contribution.withModuleContribution(contribution::contribute);
return contribution.withModuleContribution(this::contribute);
}
@Override

View File

@@ -121,7 +121,7 @@ public class TypeCollector {
private void processType(ResolvableType type, InspectionCache cache, Consumer<ResolvableType> callback) {
if (ResolvableType.NONE.equals(type) || cache.contains(type)) {
if (ResolvableType.NONE.equals(type) || cache.contains(type) || type.toClass().isSynthetic()) {
return;
}

View File

@@ -29,7 +29,7 @@ import org.springframework.core.annotation.SynthesizedAnnotation;
* @author Christoph Strobl
* @since 3.0
*/
class TypeContributor {
public class TypeContributor {
public static final String DATA_NAMESPACE = "org.springframework.data";
@@ -39,7 +39,7 @@ class TypeContributor {
* @param type
* @param contribution
*/
static void contribute(Class<?> type, GenerationContext contribution) {
public static void contribute(Class<?> type, GenerationContext contribution) {
contribute(type, Collections.emptySet(), contribution);
}
@@ -51,7 +51,7 @@ class TypeContributor {
* @param contribution
*/
@SuppressWarnings("unchecked")
static void contribute(Class<?> type, Predicate<Class<? extends Annotation>> filter, GenerationContext contribution) {
public static void contribute(Class<?> type, Predicate<Class<? extends Annotation>> filter, GenerationContext contribution) {
if (type.isPrimitive()) {
return;
@@ -76,7 +76,7 @@ class TypeContributor {
}
contribution.getRuntimeHints().reflection().registerType(type, hint ->
hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS));
hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.DECLARED_FIELDS));
}
/**
@@ -87,15 +87,15 @@ class TypeContributor {
* @param annotationNamespaces
* @param contribution
*/
static void contribute(Class<?> type, Set<String> annotationNamespaces, GenerationContext contribution) {
public static void contribute(Class<?> type, Set<String> annotationNamespaces, GenerationContext contribution) {
contribute(type, it -> isPartOfOrMetaAnnotatedWith(it, annotationNamespaces), contribution);
}
private static boolean isPartOf(Class<?> type, Set<String> namespaces) {
public static boolean isPartOf(Class<?> type, Set<String> namespaces) {
return namespaces.stream().anyMatch(namespace -> type.getPackageName().startsWith(namespace));
}
protected static boolean isPartOfOrMetaAnnotatedWith(Class<? extends Annotation> annotation, Set<String> namespaces) {
public static boolean isPartOfOrMetaAnnotatedWith(Class<? extends Annotation> annotation, Set<String> namespaces) {
if (isPartOf(annotation, namespaces)) {
return true;