Expose ApplicationContext when using SpringApplication#from
This commit returns the running application context when running an application via SpringApplication#from so that it is consistent with the regular SpringApplication#run. Closes gh-35203
This commit is contained in:
parent
10fd7517a8
commit
e6afc490b0
|
|
@ -1453,14 +1453,35 @@ public class SpringApplication {
|
|||
/**
|
||||
* Run the application using the given args.
|
||||
* @param args the main method args
|
||||
* @return the running {@link ApplicationContext}
|
||||
*/
|
||||
public void run(String... args) {
|
||||
withHook(this::getRunListener, () -> this.main.accept(args));
|
||||
public ConfigurableApplicationContext run(String... args) {
|
||||
ContextLoaderHook hook = new ContextLoaderHook(this.sources);
|
||||
withHook(hook, () -> this.main.accept(args));
|
||||
return hook.applicationContext;
|
||||
}
|
||||
|
||||
private SpringApplicationRunListener getRunListener(SpringApplication springApplication) {
|
||||
springApplication.addPrimarySources(this.sources);
|
||||
return null;
|
||||
private static class ContextLoaderHook implements SpringApplicationHook {
|
||||
|
||||
private final Set<Class<?>> sources;
|
||||
|
||||
private ConfigurableApplicationContext applicationContext;
|
||||
|
||||
ContextLoaderHook(Set<Class<?>> sources) {
|
||||
this.sources = sources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpringApplicationRunListener getRunListener(SpringApplication springApplication) {
|
||||
springApplication.addPrimarySources(this.sources);
|
||||
return new SpringApplicationRunListener() {
|
||||
@Override
|
||||
public void contextPrepared(ConfigurableApplicationContext context) {
|
||||
ContextLoaderHook.this.applicationContext = context;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1368,6 +1368,14 @@ class SpringApplicationTests {
|
|||
ExampleAdditionalConfig.local.set(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fromReturnsApplicationContext() {
|
||||
ConfigurableApplicationContext context = SpringApplication.from(ExampleFromMainMethod::main)
|
||||
.with(ExampleAdditionalConfig.class)
|
||||
.run();
|
||||
assertThat(context).isNotNull();
|
||||
}
|
||||
|
||||
private <S extends AvailabilityState> ArgumentMatcher<ApplicationEvent> isAvailabilityChangeEventWithState(
|
||||
S state) {
|
||||
return (argument) -> (argument instanceof AvailabilityChangeEvent<?>)
|
||||
|
|
|
|||
Loading…
Reference in New Issue