Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-GH-2595-SNAPSHOT</version>

<name>Spring Data Core</name>
<description>Core Spring concepts underpinning every Spring Data module.</description>
Expand Down
1 change: 1 addition & 0 deletions src/main/antora/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* xref:custom-conversions.adoc[]
* xref:entity-callbacks.adoc[]
* xref:is-new-state-detection.adoc[]
* xref:aot.adoc[]
* xref:kotlin.adoc[]
** xref:kotlin/requirements.adoc[]
** xref:kotlin/null-safety.adoc[]
Expand Down
75 changes: 75 additions & 0 deletions src/main/antora/modules/ROOT/pages/aot.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
= Ahead of Time Optimizations

This chapter covers Spring Data's Ahead of Time (AOT) optimizations that build upon {spring-framework-docs}/core/aot.html[Spring's Ahead of Time Optimizations].

[[aot.bestpractices]]
== Best Practices

=== Annotate your Domain Types

During application startup, Spring scans the classpath for domain classes for early processing of entities.
By annotating your domain types with Spring Data Store specific `@Table`, `@Document` or `@Entity` annotations you can aid initial entity scanning and ensure that those types are registered with `ManagedTypes` for Runtime Hints.
Classpath scanning is not possible in native image arrangements and so Spring has to use `ManagedTypes` for the initial entity set.

[[aot.code-gen]]
== Ahead of Time Code Generation

Ahead of time code generation is not limited to usage with GraalVM Native Image but also offers benefits when working with regular deployments and can help optimize startup performance on the jvm.

If Ahead of Time compilation is enabled Spring Data can (depending on the actual Module in use) contribute several components during the AOT phase of your build.

* Bytecode for generated Type/Property Accessors
* Sourcecode for the defined Repository Interfaces
* Repository Metadata in JSON format

Each of the above is enabled by default.
However, there users may fine tune the configuration with following options.

[options = "autowidth",cols="1,1"]
|===
|`spring.aot.data.accessors.enabled`
|Boolean flag to control contribution of Bytecode for generated Type/Property Accessors

|`spring.aot.data.accessors.include`
|Comma separated list of FQCN for which to contribute Bytecode for generated Type/Property Accessors.
Ant-style include patterns matching package names (e.g. `com.acme.**`) or type names inclusion.
Inclusion pattern matches are evaluated before exclusions for broad exclusion and selective inclusion.

|`spring.aot.data.accessors.exclude`
|Comma separated list of FQCN for which to skip contribution of Bytecode for generated Type/Property Accessors.
Ant-style exclude patterns matching package names (e.g. `com.acme.**`) or type names exclusion.
Exclusion pattern matches are evaluated after inclusions for broad exclusion and selective inclusion.

|`spring.aot.repositories.enabled`
|Boolean flag to control contribution of Source Code for Repository Interfaces

|`spring.aot.[module-name].repositories.enabled`
|Boolean flag to control contribution of Source Code for Repository Interfaces for a certain module (eg. `jdbc`, `jpa`, `mongodb`, `cassandra`)
|===

[[aot.repositories]]
== Ahead of Time Repositories

AOT Repositories are an extension to AOT processing by pre-generating eligible query method implementations.
Query methods are opaque to developers regarding their underlying queries being executed in a query method call.
AOT repositories contribute query method implementations based on derived, annotated, and named queries that are known at build-time.
This optimization moves query method processing from runtime to build-time, which can lead to a significant performance improvement as query methods do not need to be analyzed reflectively upon each application start.

The resulting AOT repository fragment follows the naming scheme of `<Repository FQCN>Impl_AotRepository` and is placed in the same package as the repository interface.

[[aot.hints]]
== Native Image Runtime Hints

Running an application as a native image requires additional information compared to a regular JVM runtime.
Spring Data contributes {spring-framework-docs}/core/aot.html#aot.hints[Runtime Hints] during AOT processing for native image usage.
These are in particular hints for:

* Auditing
* `ManagedTypes` to capture the outcome of class-path scans
* Repositories
** Reflection hints for entities, return types, and Spring Data annotations
** Repository fragments
** Querydsl `Q` classes
** Kotlin Coroutine support
* Web support (Jackson Hints for `PagedModel`)

Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,6 @@ The `exposeMetadata` flag can be set directly on the repository factory bean via
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.lang.Nullable;

@Configuration
class MyConfiguration {
Expand Down
30 changes: 28 additions & 2 deletions src/main/java/org/springframework/data/aot/AotContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.springframework.beans.factory.config.BeanReference;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.Environment;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.env.StandardEnvironment;
Expand Down Expand Up @@ -213,6 +214,33 @@ default IntrospectedBeanDefinition introspectBeanDefinition(BeanReference refere
*/
IntrospectedBeanDefinition introspectBeanDefinition(String beanName);

/**
* Obtain a {@link AotTypeConfiguration} for the given {@link ResolvableType} to customize the AOT processing for the
* given type.
*
* @param resolvableType the resolvable type to configure.
* @param configurationConsumer configuration consumer function.
*/
default void typeConfiguration(ResolvableType resolvableType, Consumer<AotTypeConfiguration> configurationConsumer) {
typeConfiguration(resolvableType.toClass(), configurationConsumer);
}

/**
* Obtain a {@link AotTypeConfiguration} for the given {@link ResolvableType} to customize the AOT processing for the
* given type.
*
* @param type the type to configure.
* @param configurationConsumer configuration consumer function.
*/
void typeConfiguration(Class<?> type, Consumer<AotTypeConfiguration> configurationConsumer);

/**
* Return all type configurations registered with this {@link AotContext}.
*
* @return all type configurations registered with this {@link AotContext}.
*/
Collection<AotTypeConfiguration> typeConfigurations();

/**
* Type-based introspector to resolve {@link Class} from a type name and to introspect the bean factory for presence
* of beans.
Expand Down Expand Up @@ -272,7 +300,6 @@ default void ifTypePresent(Consumer<Class<?>> action) {
* @return a {@link List} of bean names. The list is empty if the bean factory does not hold any beans of this type.
*/
List<String> getBeanNames();

}

/**
Expand Down Expand Up @@ -326,7 +353,6 @@ interface IntrospectedBeanDefinition {
*/
@Nullable
Class<?> resolveType();

}

}
114 changes: 114 additions & 0 deletions src/main/java/org/springframework/data/aot/AotMappingContext.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Copyright 2025 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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.mapping.Association;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.context.AbstractMappingContext;
import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty;
import org.springframework.data.mapping.model.BasicPersistentEntity;
import org.springframework.data.mapping.model.ClassGeneratingPropertyAccessorFactory;
import org.springframework.data.mapping.model.EntityInstantiator;
import org.springframework.data.mapping.model.EntityInstantiatorSource;
import org.springframework.data.mapping.model.EntityInstantiators;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.TypeInformation;

/**
* Simple {@link AbstractMappingContext} for processing of AOT contributions.
*
* @author Mark Paluch
* @since 4.0
*/
class AotMappingContext extends
AbstractMappingContext<BasicPersistentEntity<?, AotMappingContext.AotPersistentProperty>, AotMappingContext.AotPersistentProperty> {

private static final Log logger = LogFactory.getLog(AotMappingContext.class);

private final EntityInstantiators instantiators = new EntityInstantiators();
private final AotAccessorFactory propertyAccessorFactory = new AotAccessorFactory();

/**
* Contribute entity instantiators and property accessors for the given {@link PersistentEntity} that are captured
* through Spring's {@code CglibClassHandler}. Otherwise, this is a no-op if contributions are not ran through
* {@code CglibClassHandler}.
*
* @param entityType
*/
public void contribute(Class<?> entityType) {

BasicPersistentEntity<?, AotPersistentProperty> entity = getPersistentEntity(entityType);

if (entity != null) {

EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity);
if (instantiator instanceof EntityInstantiatorSource source) {
source.getInstantiatorFor(entity);
}

propertyAccessorFactory.initialize(entity);
}
}

@Override
protected <T> BasicPersistentEntity<?, AotPersistentProperty> createPersistentEntity(
TypeInformation<T> typeInformation) {
logger.debug("I hate gradle: create persistent entity for type: " + typeInformation);
return new BasicPersistentEntity<>(typeInformation);
}

@Override
protected AotPersistentProperty createPersistentProperty(Property property,
BasicPersistentEntity<?, AotPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
logger.info("creating property: " + property.getName());
return new AotPersistentProperty(property, owner, simpleTypeHolder);
}

static class AotPersistentProperty extends AnnotationBasedPersistentProperty<AotPersistentProperty> {

public AotPersistentProperty(Property property, PersistentEntity<?, AotPersistentProperty> owner,
SimpleTypeHolder simpleTypeHolder) {
super(property, owner, simpleTypeHolder);
}

@Override
public boolean isAssociation() {
return false;
}

@Override
protected Association<AotPersistentProperty> createAssociation() {
return new Association<>(this, null);
}

@Override
public Association<AotPersistentProperty> getAssociation() {
return new Association<>(this, null);
}

}

static class AotAccessorFactory extends ClassGeneratingPropertyAccessorFactory {

public void initialize(PersistentEntity<?, ?> entity) {
potentiallyCreateAndRegisterPersistentPropertyAccessorClass(entity);
}
}

}
Loading