Skip to content

Commit 87e7869

Browse files
committed
Use AOT-generated initialization when running in a native image
Closes gh-30915
1 parent c91b787 commit 87e7869

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java

+23-4
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
import org.springframework.context.support.AbstractApplicationContext;
6060
import org.springframework.context.support.GenericApplicationContext;
6161
import org.springframework.core.GenericTypeResolver;
62+
import org.springframework.core.NativeDetector;
6263
import org.springframework.core.Ordered;
6364
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
6465
import org.springframework.core.annotation.Order;
@@ -371,6 +372,7 @@ private void prepareContext(DefaultBootstrapContext bootstrapContext, Configurab
371372
ApplicationArguments applicationArguments, Banner printedBanner) {
372373
context.setEnvironment(environment);
373374
postProcessApplicationContext(context);
375+
addAotGeneratedInitializerIfNecessary(this.initializers);
374376
applyInitializers(context);
375377
listeners.contextPrepared(context);
376378
bootstrapContext.close(context);
@@ -394,13 +396,30 @@ private void prepareContext(DefaultBootstrapContext bootstrapContext, Configurab
394396
if (this.lazyInitialization) {
395397
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
396398
}
397-
// Load the sources
398-
Set<Object> sources = getAllSources();
399-
Assert.notEmpty(sources, "Sources must not be empty");
400-
load(context, sources.toArray(new Object[0]));
399+
if (!NativeDetector.inNativeImage()) {
400+
// Load the sources
401+
Set<Object> sources = getAllSources();
402+
Assert.notEmpty(sources, "Sources must not be empty");
403+
load(context, sources.toArray(new Object[0]));
404+
}
401405
listeners.contextLoaded(context);
402406
}
403407

408+
private void addAotGeneratedInitializerIfNecessary(List<ApplicationContextInitializer<?>> initializers) {
409+
if (NativeDetector.inNativeImage()) {
410+
try {
411+
Class<?> aClass = Class.forName(this.mainApplicationClass.getName() + "__ApplicationContextInitializer",
412+
true, getClassLoader());
413+
ApplicationContextInitializer<?> initializer = (ApplicationContextInitializer<?>) aClass
414+
.getDeclaredConstructor().newInstance();
415+
initializers.add(0, initializer);
416+
}
417+
catch (Exception ex) {
418+
throw new IllegalArgumentException("Failed to load AOT-generated ApplicationContextInitializer", ex);
419+
}
420+
}
421+
}
422+
404423
private boolean refreshContext(ConfigurableApplicationContext context) {
405424
if (!SpringApplicationHooks.hooks().preRefresh(this, context)) {
406425
return false;

0 commit comments

Comments
 (0)