diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index 0b6689476c8..026a804a73f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java @@ -59,6 +59,7 @@ import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.GenericTypeResolver; +import org.springframework.core.NativeDetector; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.annotation.Order; @@ -371,6 +372,7 @@ public class SpringApplication { ApplicationArguments applicationArguments, Banner printedBanner) { context.setEnvironment(environment); postProcessApplicationContext(context); + addAotGeneratedInitializerIfNecessary(this.initializers); applyInitializers(context); listeners.contextPrepared(context); bootstrapContext.close(context); @@ -394,13 +396,30 @@ public class SpringApplication { if (this.lazyInitialization) { context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } - // Load the sources - Set sources = getAllSources(); - Assert.notEmpty(sources, "Sources must not be empty"); - load(context, sources.toArray(new Object[0])); + if (!NativeDetector.inNativeImage()) { + // Load the sources + Set sources = getAllSources(); + Assert.notEmpty(sources, "Sources must not be empty"); + load(context, sources.toArray(new Object[0])); + } listeners.contextLoaded(context); } + private void addAotGeneratedInitializerIfNecessary(List> initializers) { + if (NativeDetector.inNativeImage()) { + try { + Class aClass = Class.forName(this.mainApplicationClass.getName() + "__ApplicationContextInitializer", + true, getClassLoader()); + ApplicationContextInitializer initializer = (ApplicationContextInitializer) aClass + .getDeclaredConstructor().newInstance(); + initializers.add(0, initializer); + } + catch (Exception ex) { + throw new IllegalArgumentException("Failed to load AOT-generated ApplicationContextInitializer", ex); + } + } + } + private boolean refreshContext(ConfigurableApplicationContext context) { if (!SpringApplicationHooks.hooks().preRefresh(this, context)) { return false;