Skip to content

Allow SpringApplication to create its application context without requiring reflection #22322

@dsyer

Description

@dsyer

I found I needed to access the applicationContextClass reflectively in order to reason about whether I needed to change the default. This was specifically when trying to avoid annotation-based @Configuration processing, but I guess there might be other reasons to want to do it. So adding a public accessor for SpringApplication.applicationContextClass would get me where I need to go.

Example code in Spring Init:

WebApplicationType type = getWebApplicationType(application, prepared.getEnvironment()); // assumptions made here			
Class<?> contextType = getApplicationContextType(application); // reflective access here
if (type == WebApplicationType.NONE) {
	if (contextType == AnnotationConfigApplicationContext.class || contextType == null) {
		application.setApplicationContextClass(GenericApplicationContext.class);
	}
} else if (type == WebApplicationType.REACTIVE) {
	if (contextType == AnnotationConfigReactiveWebApplicationContext.class || contextType == null) {
		application.setApplicationContextClass(ReactiveWebServerApplicationContext.class);
	}
} else if (type == WebApplicationType.SERVLET) {
	if (contextType == AnnotationConfigServletWebServerApplicationContext.class || contextType == null) {
		application.setApplicationContextClass(ServletWebServerApplicationContext.class);
	}
}

Alternatively we could encapsulate the concern of mapping a WebApplicationType to a default ApplicationContext. Even better would be to optionally avoid reflective instantiation of the ApplicationContext altogether.

Metadata

Metadata

Assignees

Labels

theme: aotAn issue related to Ahead-of-time processingtype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions