Use AOT-generated initialization when running in a native image

Closes gh-30915
pull/30984/head
Andy Wilkinson 3 years ago
parent c91b787078
commit 87e78691c4

@ -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<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[0]));
if (!NativeDetector.inNativeImage()) {
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[0]));
}
listeners.contextLoaded(context);
}
private void addAotGeneratedInitializerIfNecessary(List<ApplicationContextInitializer<?>> 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;

Loading…
Cancel
Save