Register reflection hints for Querydsl Q types.

This commit introduced support for registering GraalVM native reflection type hints for Querydsl Q types that target domain types used in the repository interface declaration.

At this point we only do a simple lookup for Q types based in the very same package that implement EntityPath.
More advanced configuration (eg. base package and type prefix), potentially available via EntityPathResolver are not taken into account as this would require eager bean resolution from the application context, which is likely to trigger additional infrastructure. In this case the user is required to register Q types manually.

Closes: #2721
Original pull request: #2743.
This commit is contained in:
Christoph Strobl
2022-12-05 14:51:10 +01:00
committed by Mark Paluch
parent 14d76ab148
commit 016e8c2779
7 changed files with 284 additions and 6 deletions

View File

@@ -31,6 +31,7 @@ import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.ResolvableType;
import org.springframework.data.domain.ManagedTypes;
import org.springframework.data.util.QTypeContributor;
import org.springframework.data.util.TypeContributor;
import org.springframework.data.util.TypeUtils;
import org.springframework.lang.Nullable;
@@ -134,9 +135,11 @@ public class ManagedTypesBeanRegistrationAotProcessor implements BeanRegistratio
Set<String> annotationNamespaces = Collections.singleton(TypeContributor.DATA_NAMESPACE);
TypeContributor.contribute(type.toClass(), annotationNamespaces, generationContext);
Class<?> resolvedType = type.toClass();
TypeContributor.contribute(resolvedType, annotationNamespaces, generationContext);
QTypeContributor.contributeEntityPath(resolvedType, generationContext, resolvedType.getClassLoader());
TypeUtils.resolveUsedAnnotations(type.toClass()).forEach(
TypeUtils.resolveUsedAnnotations(resolvedType).forEach(
annotation -> TypeContributor.contribute(annotation.getType(), annotationNamespaces, generationContext));
}

View File

@@ -42,14 +42,15 @@ import org.springframework.core.DecoratingProxy;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.aot.AotContext;
import org.springframework.data.util.TypeContributor;
import org.springframework.data.util.TypeUtils;
import org.springframework.data.projection.EntityProjectionIntrospector;
import org.springframework.data.projection.TargetAware;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.data.repository.core.support.RepositoryFragment;
import org.springframework.data.util.QTypeContributor;
import org.springframework.data.util.TypeContributor;
import org.springframework.data.util.TypeUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@@ -263,10 +264,12 @@ public class RepositoryRegistrationAotContribution implements BeanRegistrationAo
contribution.getRuntimeHints().reflection()
.registerType(repositoryInformation.getRepositoryInterface(),
hint -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS))
.registerType(repositoryInformation.getRepositoryBaseClass(),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS));
.registerType(repositoryInformation.getRepositoryBaseClass(), hint -> hint
.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS));
TypeContributor.contribute(repositoryInformation.getDomainType(), contribution);
QTypeContributor.contributeEntityPath(repositoryInformation.getDomainType(), contribution,
repositoryContext.getClassLoader());
// Repository Fragments
for (RepositoryFragment<?> fragment : getRepositoryInformation().getFragments()) {

View File

@@ -0,0 +1,109 @@
/*
* 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.util;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.function.Function;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.TypeReference;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
/**
* @author Christoph Strobl
* @since 4.1
*/
public class QTypeContributor {
private final static Log logger = LogFactory.getLog(QTypeContributor.class);
private static Function<ClassLoader, Class<?>> entityPathType = cacheOf(QTypeContributor::getEntityPathType);
public static void contributeEntityPath(Class<?> type, GenerationContext context, @Nullable ClassLoader classLoader) {
Class<?> entityPathType = QTypeContributor.entityPathType.apply(classLoader);
if (entityPathType == null) {
return;
}
String queryClassName = getQueryClassName(type);
if (ClassUtils.isPresent(queryClassName, classLoader)) {
try {
if (ClassUtils.isAssignable(entityPathType, ClassUtils.forName(queryClassName, classLoader))) {
logger.debug("Registering Q type %s for %s.");
context.getRuntimeHints().reflection().registerType(TypeReference.of(queryClassName),
MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS);
} else {
logger.debug("Skipping Q type %s. Not an EntityPath.");
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException("%s could not be loaded".formatted(queryClassName), e);
}
}
}
@Nullable
private static Class<?> getEntityPathType(ClassLoader classLoader) {
if (!ClassUtils.isPresent("com.querydsl.core.types.EntityPath", classLoader)) {
return null;
}
try {
return ClassUtils.forName("com.querydsl.core.types.EntityPath", classLoader);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static Function<ClassLoader, Class<?>> cacheOf(Function<ClassLoader, Class<?>> inFunction) {
Map<ClassLoader, Class<?>> cache = new WeakHashMap<>();
return in -> cache.computeIfAbsent(in, inFunction::apply);
}
/**
* Returns the name of the query class for the given domain class.
*
* @param domainClass
* @return
*/
private static String getQueryClassName(Class<?> domainClass) {
String simpleClassName = ClassUtils.getShortName(domainClass);
String pkgName = domainClass.getPackage().getName();
return String.format("%s.Q%s%s", pkgName, getClassBase(simpleClassName), domainClass.getSimpleName());
}
/**
* Analyzes the short class name and potentially returns the outer class.
*
* @param shortName
* @return
*/
private static String getClassBase(String shortName) {
String[] parts = shortName.split("\\.");
return parts.length < 2 ? "" : parts[0] + "_";
}
}