Class SpringApplication
java.lang.Object
org.springframework.boot.SpringApplication
Class that can be used to bootstrap and launch a Spring application from a Java main
method. By default class will perform the following steps to bootstrap your
application:
- Create an appropriate ApplicationContextinstance (depending on your classpath)
- Register a CommandLinePropertySourceto expose command line arguments as Spring properties
- Refresh the application context, loading all singleton beans
- Trigger any CommandLineRunnerbeans
run(Class, String[]) method can be called
directly from your main method to bootstrap your application:
@Configuration
@EnableAutoConfiguration
public class MyApplication  {
  // ... Bean definitions
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}
For more advanced configuration a SpringApplication instance can be created and
customized before being run:
public static void main(String[] args) {
  SpringApplication application = new SpringApplication(MyApplication.class);
  // ... customize application settings here
  application.run(args)
}
SpringApplications can read beans from a variety of different sources. It is
generally recommended that a single @Configuration class is used to bootstrap
your application, however, you may also set sources from:
- The fully qualified class name to be loaded by
AnnotatedBeanDefinitionReader
- The location of an XML resource to be loaded by XmlBeanDefinitionReader, or a groovy script to be loaded byGroovyBeanDefinitionReader
- The name of a package to be scanned by ClassPathBeanDefinitionScanner
SpringApplication. This makes it
possible to set SpringApplication properties dynamically, like additional
sources ("spring.main.sources" - a CSV list) the flag to indicate a web environment
("spring.main.web-application-type=none") or the flag to switch off the banner
("spring.main.banner-mode=off").- Since:
- 1.0.0
- Author:
- Phillip Webb, Dave Syer, Andy Wilkinson, Christian Dupuis, Stephane Nicoll, Jeremy Rickard, Craig Burke, Michael Simons, Madhura Bhave, Brian Clozel, Ethan Rubinson, Chris Bono, Moritz Halbritter, Tadaya Tsuyukubo, Lasse Wulff, Yanming Zhou
- See Also:
- 
Nested Class SummaryNested ClassesModifier and TypeClassDescriptionstatic classException that can be thrown to silently exit a runningSpringApplicationwithout handling run failures.static classUsed to configure and run an augmentedSpringApplicationwhere additional configuration should be applied.static interfaceProvides access to details of aSpringApplicationrun usingSpringApplication.Augmented.run(String...).
- 
Field SummaryFields
- 
Constructor SummaryConstructorsConstructorDescriptionSpringApplication(Class<?>... primarySources) Create a newSpringApplicationinstance.SpringApplication(@Nullable ResourceLoader resourceLoader, Class<?>... primarySources) Create a newSpringApplicationinstance.
- 
Method SummaryModifier and TypeMethodDescriptionvoidaddBootstrapRegistryInitializer(BootstrapRegistryInitializer bootstrapRegistryInitializer) AddsBootstrapRegistryInitializerinstances that can be used to initialize theBootstrapRegistry.voidaddInitializers(ApplicationContextInitializer<?>... initializers) AddApplicationContextInitializers to be applied to the SpringApplicationContext.voidaddListeners(ApplicationListener<?>... listeners) AddApplicationListeners to be applied to the SpringApplication and registered with theApplicationContext.voidaddPrimarySources(Collection<Class<?>> additionalPrimarySources) Add additional items to the primary sources that will be added to an ApplicationContext whenrun(String...)is called.protected voidafterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) Called after the context has been refreshed.protected voidApply anyApplicationContextInitializers to the context before it is refreshed.protected voidbindToSpringApplication(ConfigurableEnvironment environment) Bind the environment to theApplicationProperties.protected voidconfigureEnvironment(ConfigurableEnvironment environment, String[] args) Template method delegating toconfigurePropertySources(ConfigurableEnvironment, String[])andconfigureProfiles(ConfigurableEnvironment, String[])in that order.protected voidconfigureProfiles(ConfigurableEnvironment environment, String[] args) Configure which profiles are active (or active by default) for this application environment.protected voidconfigurePropertySources(ConfigurableEnvironment environment, String[] args) Add, remove or re-order anyPropertySources in this application's environment.protected ConfigurableApplicationContextStrategy method used to create theApplicationContext.protected org.springframework.boot.BeanDefinitionLoadercreateBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) Factory method used to create theBeanDefinitionLoader.static intexit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) Static helper that can be used to exit aSpringApplicationand obtain a code indicating success (0) or otherwise.static SpringApplication.Augmentedfrom(ThrowingConsumer<String[]> main) Create an application from an existingmainmethod that can run with additional@Configurationor bean classes.Return an immutable set of any additional profiles in use.Return an immutable set of all the sources that will be added to an ApplicationContext whenrun(String...)is called.protected org.apache.commons.logging.LogReturns theLogfor the application.Returns theApplicationStartupused for collecting startup metrics.Either the ClassLoader that will be used in the ApplicationContext (ifresourceLoaderis set), or the context class loader (if not null), or the loader of the SpringClassUtilsclass.@Nullable StringReturn a prefix that should be applied when obtaining configuration properties from the system environment.Returns read-only ordered Set of theApplicationContextInitializers that will be applied to the SpringApplicationContext.Returns read-only ordered Set of theApplicationListeners that will be applied to the SpringApplication and registered with theApplicationContext.@Nullable Class<?> Returns the main application class that has been deduced or explicitly configured.@Nullable ResourceLoaderThe ResourceLoader that will be used in the ApplicationContext.Return aSpringApplicationShutdownHandlersinstance that can be used to add or remove handlers that perform actions before the JVM is shutdown.Returns a mutable set of the sources that will be added to an ApplicationContext whenrun(String...)is called.@Nullable WebApplicationTypeReturns the type of web application that is being run.booleanWhether to keep the application alive even if there are no more non-daemon threads.protected voidload(ApplicationContext context, Object[] sources) Load beans into the application context.protected voidCalled to log startup information, subclasses may override to add additional logging.protected voidCalled to log active profile information.static voidA basic main that can be used to launch an application.protected voidApply any relevant post-processing to theApplicationContext.protected voidrefresh(ConfigurableApplicationContext applicationContext) Refresh the underlyingApplicationContext.protected voidregisterLoggedException(Throwable exception) Register that the given exception has been logged.Static helper that can be used to run aSpringApplicationfrom the specified sources using default settings and user supplied arguments.Static helper that can be used to run aSpringApplicationfrom the specified source using default settings.Run the Spring application, creating and refreshing a newApplicationContext.voidsetAddCommandLineProperties(boolean addCommandLineProperties) Sets if aCommandLinePropertySourceshould be added to the application context in order to expose arguments.voidsetAddConversionService(boolean addConversionService) Sets if theApplicationConversionServiceshould be added to the application context'sEnvironment.voidsetAdditionalProfiles(String... profiles) Set additional profile values to use (on top of those set in system or command line properties).voidsetAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) Sets if bean definition overriding, by registering a definition with the same name as an existing definition, should be allowed.voidsetAllowCircularReferences(boolean allowCircularReferences) Sets whether to allow circular references between beans and automatically try to resolve them.voidsetApplicationContextFactory(@Nullable ApplicationContextFactory applicationContextFactory) Sets the factory that will be called to create the application context.voidsetApplicationStartup(ApplicationStartup applicationStartup) Set theApplicationStartupto use for collecting startup metrics.voidSets theBannerinstance which will be used to print the banner when no static banner file is provided.voidsetBannerMode(Banner.Mode bannerMode) Sets the mode used to display the banner when the application runs.voidsetBeanNameGenerator(BeanNameGenerator beanNameGenerator) Sets the bean name generator that should be used when generating bean names.voidsetDefaultProperties(Map<String, Object> defaultProperties) Set default environment properties which will be used in addition to those in the existingEnvironment.voidsetDefaultProperties(Properties defaultProperties) Convenient alternative tosetDefaultProperties(Map).voidsetEnvironment(@Nullable ConfigurableEnvironment environment) Sets the underlying environment that should be used with the created application context.voidsetEnvironmentPrefix(String environmentPrefix) Set the prefix that should be applied when obtaining configuration properties from the system environment.voidsetHeadless(boolean headless) Sets if the application is headless and should not instantiate AWT.voidsetInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) Sets theApplicationContextInitializerthat will be applied to the SpringApplicationContext.voidsetKeepAlive(boolean keepAlive) Set whether to keep the application alive even if there are no more non-daemon threads.voidsetLazyInitialization(boolean lazyInitialization) Sets if beans should be initialized lazily.voidsetListeners(Collection<? extends ApplicationListener<?>> listeners) Sets theApplicationListeners that will be applied to the SpringApplication and registered with theApplicationContext.voidsetLogStartupInfo(boolean logStartupInfo) Sets if the application information should be logged when the application starts.voidsetMainApplicationClass(@Nullable Class<?> mainApplicationClass) Set a specific main application class that will be used as a log source and to obtain version information.voidsetRegisterShutdownHook(boolean registerShutdownHook) Sets if the createdApplicationContextshould have a shutdown hook registered.voidsetResourceLoader(ResourceLoader resourceLoader) Sets theResourceLoaderthat should be used when loading resources.voidsetSources(Set<String> sources) Set additional sources that will be used to create an ApplicationContext.voidsetWebApplicationType(WebApplicationType webApplicationType) Sets the type of web application to be run.static voidwithHook(SpringApplicationHook hook, Runnable action) Perform the given action with the givenSpringApplicationHookattached if the action triggers anapplication run.static <T> TwithHook(SpringApplicationHook hook, ThrowingSupplier<T> action) Perform the given action with the givenSpringApplicationHookattached if the action triggers anapplication run.
- 
Field Details- 
BANNER_LOCATION_PROPERTY_VALUE
- 
BANNER_LOCATION_PROPERTY
 
- 
- 
Constructor Details- 
SpringApplicationCreate a newSpringApplicationinstance. The application context will load beans from the specified primary sources (seeclass-leveldocumentation for details). The instance can be customized before callingrun(String...).- Parameters:
- primarySources- the primary bean sources
- See Also:
 
- 
SpringApplicationCreate a newSpringApplicationinstance. The application context will load beans from the specified primary sources (seeclass-leveldocumentation for details). The instance can be customized before callingrun(String...).- Parameters:
- resourceLoader- the resource loader to use
- primarySources- the primary bean sources
- See Also:
 
 
- 
- 
Method Details- 
runRun the Spring application, creating and refreshing a newApplicationContext.- Parameters:
- args- the application arguments (usually passed from a Java main method)
- Returns:
- a running ApplicationContext
 
- 
configureEnvironmentTemplate method delegating toconfigurePropertySources(ConfigurableEnvironment, String[])andconfigureProfiles(ConfigurableEnvironment, String[])in that order. Override this method for complete control over Environment customization, or one of the above for fine-grained control over property sources or profiles, respectively.- Parameters:
- environment- this application's environment
- args- arguments passed to the- runmethod
- See Also:
 
- 
configurePropertySourcesAdd, remove or re-order anyPropertySources in this application's environment.- Parameters:
- environment- this application's environment
- args- arguments passed to the- runmethod
- See Also:
 
- 
configureProfilesConfigure which profiles are active (or active by default) for this application environment. Additional profiles may be activated during configuration file processing through thespring.profiles.activeproperty.- Parameters:
- environment- this application's environment
- args- arguments passed to the- runmethod
- See Also:
 
- 
bindToSpringApplicationBind the environment to theApplicationProperties.- Parameters:
- environment- the environment to bind
 
- 
createApplicationContextStrategy method used to create theApplicationContext. By default this method will respect any explicitly set application context class or factory before falling back to a suitable default.- Returns:
- the application context (not yet refreshed)
- See Also:
 
- 
postProcessApplicationContextApply any relevant post-processing to theApplicationContext. Subclasses can apply additional processing as required.- Parameters:
- context- the application context
 
- 
applyInitializersApply anyApplicationContextInitializers to the context before it is refreshed.- Parameters:
- context- the configured ApplicationContext (not refreshed yet)
- See Also:
 
- 
logStartupInfoCalled to log startup information, subclasses may override to add additional logging.- Parameters:
- context- the application context
- Since:
- 3.4.0
 
- 
logStartupProfileInfoCalled to log active profile information.- Parameters:
- context- the application context
 
- 
getApplicationLogprotected org.apache.commons.logging.Log getApplicationLog()Returns theLogfor the application. By default will be deduced.- Returns:
- the application log
 
- 
loadLoad beans into the application context.- Parameters:
- context- the context to load beans into
- sources- the sources to load
 
- 
getResourceLoaderThe ResourceLoader that will be used in the ApplicationContext.- Returns:
- the resourceLoader the resource loader that will be used in the
ApplicationContext (or nullif the default)
 
- 
getClassLoaderEither the ClassLoader that will be used in the ApplicationContext (ifresourceLoaderis set), or the context class loader (if not null), or the loader of the SpringClassUtilsclass.- Returns:
- a ClassLoader (never null)
 
- 
createBeanDefinitionLoaderprotected org.springframework.boot.BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) Factory method used to create theBeanDefinitionLoader.- Parameters:
- registry- the bean definition registry
- sources- the sources to load
- Returns:
- the BeanDefinitionLoaderthat will be used to load beans
 
- 
refreshRefresh the underlyingApplicationContext.- Parameters:
- applicationContext- the application context to refresh
 
- 
afterRefreshCalled after the context has been refreshed.- Parameters:
- context- the application context
- args- the application arguments
 
- 
registerLoggedExceptionRegister that the given exception has been logged. By default, if the running in the main thread, this method will suppress additional printing of the stacktrace.- Parameters:
- exception- the exception that was logged
 
- 
getMainApplicationClassReturns the main application class that has been deduced or explicitly configured.- Returns:
- the main application class or null
 
- 
setMainApplicationClassSet a specific main application class that will be used as a log source and to obtain version information. By default the main application class will be deduced. Can be set tonullif there is no explicit application class.- Parameters:
- mainApplicationClass- the mainApplicationClass to set or- null
 
- 
getWebApplicationTypeReturns the type of web application that is being run.- Returns:
- the type of web application
- Since:
- 2.0.0
 
- 
setWebApplicationTypeSets the type of web application to be run. If not explicitly set the type of web application will be deduced based on the classpath.- Parameters:
- webApplicationType- the web application type
- Since:
- 2.0.0
 
- 
setAllowBeanDefinitionOverridingpublic void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) Sets if bean definition overriding, by registering a definition with the same name as an existing definition, should be allowed. Defaults tofalse.- Parameters:
- allowBeanDefinitionOverriding- if overriding is allowed
- Since:
- 2.1.0
- See Also:
 
- 
setAllowCircularReferencespublic void setAllowCircularReferences(boolean allowCircularReferences) Sets whether to allow circular references between beans and automatically try to resolve them. Defaults tofalse.- Parameters:
- allowCircularReferences- if circular references are allowed
- Since:
- 2.6.0
- See Also:
 
- 
setLazyInitializationpublic void setLazyInitialization(boolean lazyInitialization) Sets if beans should be initialized lazily. Defaults tofalse.- Parameters:
- lazyInitialization- if initialization should be lazy
- Since:
- 2.2
- See Also:
 
- 
setHeadlesspublic void setHeadless(boolean headless) Sets if the application is headless and should not instantiate AWT. Defaults totrueto prevent java icons appearing.- Parameters:
- headless- if the application is headless
 
- 
setRegisterShutdownHookpublic void setRegisterShutdownHook(boolean registerShutdownHook) Sets if the createdApplicationContextshould have a shutdown hook registered. Defaults totrueto ensure that JVM shutdowns are handled gracefully.- Parameters:
- registerShutdownHook- if the shutdown hook should be registered
- See Also:
 
- 
setBanner
- 
setBannerModeSets the mode used to display the banner when the application runs. Defaults toBanner.Mode.CONSOLE.- Parameters:
- bannerMode- the mode used to display the banner
 
- 
setLogStartupInfopublic void setLogStartupInfo(boolean logStartupInfo) Sets if the application information should be logged when the application starts. Defaults totrue.- Parameters:
- logStartupInfo- if startup info should be logged.
 
- 
setAddCommandLinePropertiespublic void setAddCommandLineProperties(boolean addCommandLineProperties) Sets if aCommandLinePropertySourceshould be added to the application context in order to expose arguments. Defaults totrue.- Parameters:
- addCommandLineProperties- if command line arguments should be exposed
 
- 
setAddConversionServicepublic void setAddConversionService(boolean addConversionService) Sets if theApplicationConversionServiceshould be added to the application context'sEnvironment.- Parameters:
- addConversionService- if the application conversion service should be added
- Since:
- 2.1.0
 
- 
addBootstrapRegistryInitializerpublic void addBootstrapRegistryInitializer(BootstrapRegistryInitializer bootstrapRegistryInitializer) AddsBootstrapRegistryInitializerinstances that can be used to initialize theBootstrapRegistry.- Parameters:
- bootstrapRegistryInitializer- the bootstrap registry initializer to add
- Since:
- 2.4.5
 
- 
setDefaultPropertiesSet default environment properties which will be used in addition to those in the existingEnvironment.- Parameters:
- defaultProperties- the additional properties to set
 
- 
setDefaultPropertiesConvenient alternative tosetDefaultProperties(Map).- Parameters:
- defaultProperties- some- Properties
 
- 
setAdditionalProfilesSet additional profile values to use (on top of those set in system or command line properties).- Parameters:
- profiles- the additional profiles to set
 
- 
getAdditionalProfiles
- 
setBeanNameGeneratorSets the bean name generator that should be used when generating bean names.- Parameters:
- beanNameGenerator- the bean name generator
 
- 
setEnvironmentSets the underlying environment that should be used with the created application context.- Parameters:
- environment- the environment
 
- 
addPrimarySourcesAdd additional items to the primary sources that will be added to an ApplicationContext whenrun(String...)is called.The sources here are added to those that were set in the constructor. Most users should consider using getSources()/setSources(Set)rather than calling this method.- Parameters:
- additionalPrimarySources- the additional primary sources to add
- See Also:
 
- 
getSourcesReturns a mutable set of the sources that will be added to an ApplicationContext whenrun(String...)is called.Sources set here will be used in addition to any primary sources set in the constructor. - Returns:
- the application sources.
- See Also:
 
- 
setSourcesSet additional sources that will be used to create an ApplicationContext. A source can be: a class name, package name, or an XML resource location.Sources set here will be used in addition to any primary sources set in the constructor. - Parameters:
- sources- the application sources to set
- See Also:
 
- 
getAllSourcesReturn an immutable set of all the sources that will be added to an ApplicationContext whenrun(String...)is called. This method combines any primary sources specified in the constructor with any additional ones that have beenexplicitly set.- Returns:
- an immutable set of all sources
 
- 
setResourceLoaderSets theResourceLoaderthat should be used when loading resources.- Parameters:
- resourceLoader- the resource loader
 
- 
getEnvironmentPrefixReturn a prefix that should be applied when obtaining configuration properties from the system environment.- Returns:
- the environment property prefix
- Since:
- 2.5.0
 
- 
setEnvironmentPrefixSet the prefix that should be applied when obtaining configuration properties from the system environment.- Parameters:
- environmentPrefix- the environment property prefix to set
- Since:
- 2.5.0
 
- 
setApplicationContextFactorypublic void setApplicationContextFactory(@Nullable ApplicationContextFactory applicationContextFactory) Sets the factory that will be called to create the application context. If not set, defaults to a factory that will create a context that is appropriate for the application's type (a reactive web application, a servlet web application, or a non-web application).- Parameters:
- applicationContextFactory- the factory for the context
- Since:
- 2.4.0
 
- 
setInitializersSets theApplicationContextInitializerthat will be applied to the SpringApplicationContext.- Parameters:
- initializers- the initializers to set
 
- 
addInitializersAddApplicationContextInitializers to be applied to the SpringApplicationContext.- Parameters:
- initializers- the initializers to add
 
- 
getInitializersReturns read-only ordered Set of theApplicationContextInitializers that will be applied to the SpringApplicationContext.- Returns:
- the initializers
 
- 
setListenersSets theApplicationListeners that will be applied to the SpringApplication and registered with theApplicationContext.- Parameters:
- listeners- the listeners to set
 
- 
addListenersAddApplicationListeners to be applied to the SpringApplication and registered with theApplicationContext.- Parameters:
- listeners- the listeners to add
 
- 
getListenersReturns read-only ordered Set of theApplicationListeners that will be applied to the SpringApplication and registered with theApplicationContext.- Returns:
- the listeners
 
- 
setApplicationStartupSet theApplicationStartupto use for collecting startup metrics.- Parameters:
- applicationStartup- the application startup to use
- Since:
- 2.4.0
 
- 
getApplicationStartupReturns theApplicationStartupused for collecting startup metrics.- Returns:
- the application startup
- Since:
- 2.4.0
 
- 
isKeepAlivepublic boolean isKeepAlive()Whether to keep the application alive even if there are no more non-daemon threads.- Returns:
- whether to keep the application alive even if there are no more non-daemon threads
- Since:
- 3.2.0
 
- 
setKeepAlivepublic void setKeepAlive(boolean keepAlive) Set whether to keep the application alive even if there are no more non-daemon threads.- Parameters:
- keepAlive- whether to keep the application alive even if there are no more non-daemon threads
- Since:
- 3.2.0
 
- 
getShutdownHandlersReturn aSpringApplicationShutdownHandlersinstance that can be used to add or remove handlers that perform actions before the JVM is shutdown.- Returns:
- a SpringApplicationShutdownHandlersinstance
- Since:
- 2.5.1
 
- 
runStatic helper that can be used to run aSpringApplicationfrom the specified source using default settings.- Parameters:
- primarySource- the primary source to load
- args- the application arguments (usually passed from a Java main method)
- Returns:
- the running ApplicationContext
 
- 
runStatic helper that can be used to run aSpringApplicationfrom the specified sources using default settings and user supplied arguments.- Parameters:
- primarySources- the primary sources to load
- args- the application arguments (usually passed from a Java main method)
- Returns:
- the running ApplicationContext
 
- 
mainA basic main that can be used to launch an application. This method is useful when application sources are defined through a --spring.main.sources command line argument.Most developers will want to define their own main method and call the runmethod instead.- Parameters:
- args- command line arguments
- Throws:
- Exception- if the application cannot be started
- See Also:
 
- 
exitStatic helper that can be used to exit aSpringApplicationand obtain a code indicating success (0) or otherwise. Does not throw exceptions but should print stack traces of any encountered. Applies the specifiedExitCodeGeneratorsin addition to any Spring beans that implementExitCodeGenerator. When multiple generators are available, the first non-zero exit code is used. Generators are ordered based on theirOrderedimplementation and@Orderannotation.- Parameters:
- context- the context to close if possible
- exitCodeGenerators- exit code generators
- Returns:
- the outcome (0 if successful)
 
- 
fromCreate an application from an existingmainmethod that can run with additional@Configurationor bean classes. This method can be helpful when writing a test harness that needs to start an application with additional configuration.- Parameters:
- main- the main method entry point that runs the- SpringApplication
- Returns:
- a SpringApplication.Augmentedinstance that can be used to add configuration and run the application
- Since:
- 3.1.0
- See Also:
 
- 
withHookPerform the given action with the givenSpringApplicationHookattached if the action triggers anapplication run.- Parameters:
- hook- the hook to apply
- action- the action to run
- Since:
- 3.0.0
- See Also:
 
- 
withHookPerform the given action with the givenSpringApplicationHookattached if the action triggers anapplication run.- Type Parameters:
- T- the result type
- Parameters:
- hook- the hook to apply
- action- the action to run
- Returns:
- the result of the action
- Since:
- 3.0.0
- See Also:
 
 
-