59
59
import org .springframework .context .support .AbstractApplicationContext ;
60
60
import org .springframework .context .support .GenericApplicationContext ;
61
61
import org .springframework .core .GenericTypeResolver ;
62
+ import org .springframework .core .NativeDetector ;
62
63
import org .springframework .core .Ordered ;
63
64
import org .springframework .core .annotation .AnnotationAwareOrderComparator ;
64
65
import org .springframework .core .annotation .Order ;
@@ -371,6 +372,7 @@ private void prepareContext(DefaultBootstrapContext bootstrapContext, Configurab
371
372
ApplicationArguments applicationArguments , Banner printedBanner ) {
372
373
context .setEnvironment (environment );
373
374
postProcessApplicationContext (context );
375
+ addAotGeneratedInitializerIfNecessary (this .initializers );
374
376
applyInitializers (context );
375
377
listeners .contextPrepared (context );
376
378
bootstrapContext .close (context );
@@ -394,13 +396,30 @@ private void prepareContext(DefaultBootstrapContext bootstrapContext, Configurab
394
396
if (this .lazyInitialization ) {
395
397
context .addBeanFactoryPostProcessor (new LazyInitializationBeanFactoryPostProcessor ());
396
398
}
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
+ }
401
405
listeners .contextLoaded (context );
402
406
}
403
407
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
+
404
423
private boolean refreshContext (ConfigurableApplicationContext context ) {
405
424
if (!SpringApplicationHooks .hooks ().preRefresh (this , context )) {
406
425
return false ;
0 commit comments