File tree Expand file tree Collapse file tree 2 files changed +34
-5
lines changed
spring-boot-project/spring-boot/src
main/java/org/springframework/boot
test/java/org/springframework/boot Expand file tree Collapse file tree 2 files changed +34
-5
lines changed Original file line number Diff line number Diff line change @@ -1453,14 +1453,35 @@ public Augmented with(Class<?>... sources) {
14531453 /**
14541454 * Run the application using the given args.
14551455 * @param args the main method args
1456+ * @return the running {@link ApplicationContext}
14561457 */
1457- public void run (String ... args ) {
1458- withHook (this ::getRunListener , () -> this .main .accept (args ));
1458+ public ConfigurableApplicationContext run (String ... args ) {
1459+ ContextLoaderHook hook = new ContextLoaderHook (this .sources );
1460+ withHook (hook , () -> this .main .accept (args ));
1461+ return hook .applicationContext ;
14591462 }
14601463
1461- private SpringApplicationRunListener getRunListener (SpringApplication springApplication ) {
1462- springApplication .addPrimarySources (this .sources );
1463- return null ;
1464+ private static class ContextLoaderHook implements SpringApplicationHook {
1465+
1466+ private final Set <Class <?>> sources ;
1467+
1468+ private ConfigurableApplicationContext applicationContext ;
1469+
1470+ ContextLoaderHook (Set <Class <?>> sources ) {
1471+ this .sources = sources ;
1472+ }
1473+
1474+ @ Override
1475+ public SpringApplicationRunListener getRunListener (SpringApplication springApplication ) {
1476+ springApplication .addPrimarySources (this .sources );
1477+ return new SpringApplicationRunListener () {
1478+ @ Override
1479+ public void contextPrepared (ConfigurableApplicationContext context ) {
1480+ ContextLoaderHook .this .applicationContext = context ;
1481+ }
1482+ };
1483+ }
1484+
14641485 }
14651486
14661487 }
Original file line number Diff line number Diff line change @@ -1368,6 +1368,14 @@ void fromRunsWithAdditionalSources() {
13681368 ExampleAdditionalConfig .local .set (null );
13691369 }
13701370
1371+ @ Test
1372+ void fromReturnsApplicationContext () {
1373+ ConfigurableApplicationContext context = SpringApplication .from (ExampleFromMainMethod ::main )
1374+ .with (ExampleAdditionalConfig .class )
1375+ .run ();
1376+ assertThat (context ).isNotNull ();
1377+ }
1378+
13711379 private <S extends AvailabilityState > ArgumentMatcher <ApplicationEvent > isAvailabilityChangeEventWithState (
13721380 S state ) {
13731381 return (argument ) -> (argument instanceof AvailabilityChangeEvent <?>)
You can’t perform that action at this time.
0 commit comments