Allow SpringApplicationBuilder to specify a ResourceLoader

See gh-26690
This commit is contained in:
Jamin Hitchcock
2021-05-27 21:39:37 -05:00
committed by Stephane Nicoll
parent 41e00e11c4
commit 7b0ba35025
2 changed files with 32 additions and 1 deletions

View File

@@ -94,7 +94,11 @@ public class SpringApplicationBuilder {
private boolean configuredAsChild = false;
public SpringApplicationBuilder(Class<?>... sources) {
this.application = createSpringApplication(sources);
this.application = createSpringApplication(null, sources);
}
public SpringApplicationBuilder(ResourceLoader resourceLoader, Class<?>... sources) {
this.application = createSpringApplication(resourceLoader, sources);
}
/**
@@ -104,11 +108,28 @@ public class SpringApplicationBuilder {
* @param sources the sources
* @return the {@link org.springframework.boot.SpringApplication} instance
* @since 1.1.0
* @deprecated Use {@link #createSpringApplication(ResourceLoader, Class...)} with
* null resource loader
*/
protected SpringApplication createSpringApplication(Class<?>... sources) {
return new SpringApplication(sources);
}
/**
* Creates a new {@link org.springframework.boot.SpringApplication} instances from the
* given sources. Subclasses may override in order to provide a custom subclass of
* {@link org.springframework.boot.SpringApplication}
* @param resourceLoader the resource loader, can be null to use default resource
* loader (see
* {@link org.springframework.boot.SpringApplication#SpringApplication(ResourceLoader, Class...)})
* @param sources the sources
* @return the {@link org.springframework.boot.SpringApplication} instance
* @since 2.5.0
*/
protected SpringApplication createSpringApplication(ResourceLoader resourceLoader, Class<?>... sources) {
return new SpringApplication(resourceLoader, sources);
}
/**
* Accessor for the current application context.
* @return the current application context (or null if not yet running)

View File

@@ -309,6 +309,16 @@ class SpringApplicationBuilderTests {
assertThat(builder.application().getEnvironmentPrefix()).isEqualTo("test");
}
@Test
void createWithResourceLoader() {
ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader());
SpringApplicationBuilder application = new SpringApplicationBuilder(new DefaultResourceLoader(classLoader),
ExampleConfig.class)
.contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class));
this.context = application.run();
assertThat(this.context.getClassLoader()).isEqualTo(classLoader);
}
@Configuration(proxyBeanMethods = false)
static class ExampleConfig {