public class SpringApplication extends Object
ApplicationContext
instance (depending on your
classpath)CommandLinePropertySource
to expose command line arguments as
Spring propertiesCommandLineRunner
beansrun(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) }
SpringApplication
s 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:
AnnotatedBeanDefinitionReader
XmlBeanDefinitionReader
, or
a groovy script to be loaded by GroovyBeanDefinitionReader
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").run(Class, String[])
,
run(Class[], String[])
,
SpringApplication(Class...)
Modifier and Type | Field and Description |
---|---|
static String |
BANNER_LOCATION_PROPERTY
Banner location property key.
|
static String |
BANNER_LOCATION_PROPERTY_VALUE
Default banner location.
|
static String |
DEFAULT_CONTEXT_CLASS
Deprecated.
since 2.4.0 for removal in 2.6.0 in favor of using a
ApplicationContextFactory |
static String |
DEFAULT_REACTIVE_WEB_CONTEXT_CLASS
Deprecated.
since 2.4.0 for removal in 2.6.0 in favor of using an
ApplicationContextFactory |
static String |
DEFAULT_SERVLET_WEB_CONTEXT_CLASS
Deprecated.
since 2.4.0 for removal in 2.6.0 in favor of using an
ApplicationContextFactory |
Constructor and Description |
---|
SpringApplication(Class<?>... primarySources)
Create a new
SpringApplication instance. |
SpringApplication(ResourceLoader resourceLoader,
Class<?>... primarySources)
Create a new
SpringApplication instance. |
Modifier and Type | Method and Description |
---|---|
void |
addBootstrapper(Bootstrapper bootstrapper)
Deprecated.
since 2.4.5 for removal in 2.6 in favor of
addBootstrapRegistryInitializer(BootstrapRegistryInitializer) |
void |
addBootstrapRegistryInitializer(BootstrapRegistryInitializer bootstrapRegistryInitializer)
Adds
BootstrapRegistryInitializer instances that can be used to initialize
the BootstrapRegistry . |
void |
addInitializers(ApplicationContextInitializer<?>... initializers)
Add
ApplicationContextInitializer s to be applied to the Spring
ApplicationContext . |
void |
addListeners(ApplicationListener<?>... listeners)
Add
ApplicationListener s to be applied to the SpringApplication and
registered with the ApplicationContext . |
void |
addPrimarySources(Collection<Class<?>> additionalPrimarySources)
Add additional items to the primary sources that will be added to an
ApplicationContext when
run(String...) is called. |
protected void |
afterRefresh(ConfigurableApplicationContext context,
ApplicationArguments args)
Called after the context has been refreshed.
|
protected void |
applyInitializers(ConfigurableApplicationContext context)
Apply any
ApplicationContextInitializer s to the context before it is
refreshed. |
protected void |
bindToSpringApplication(ConfigurableEnvironment environment)
Bind the environment to the
SpringApplication . |
protected void |
configureEnvironment(ConfigurableEnvironment environment,
String[] args)
Template method delegating to
configurePropertySources(ConfigurableEnvironment, String[]) and
configureProfiles(ConfigurableEnvironment, String[]) in that order. |
protected void |
configureProfiles(ConfigurableEnvironment environment,
String[] args)
Configure which profiles are active (or active by default) for this application
environment.
|
protected void |
configurePropertySources(ConfigurableEnvironment environment,
String[] args)
Add, remove or re-order any
PropertySource s in this application's
environment. |
StandardEnvironment |
convertEnvironment(ConfigurableEnvironment environment)
Deprecated.
since 2.5.8 for removal in 2.7.0
|
protected ConfigurableApplicationContext |
createApplicationContext()
Strategy method used to create the
ApplicationContext . |
protected org.springframework.boot.BeanDefinitionLoader |
createBeanDefinitionLoader(BeanDefinitionRegistry registry,
Object[] sources)
Factory method used to create the
BeanDefinitionLoader . |
static int |
exit(ApplicationContext context,
ExitCodeGenerator... exitCodeGenerators)
Static helper that can be used to exit a
SpringApplication and obtain a
code indicating success (0) or otherwise. |
Set<String> |
getAdditionalProfiles()
Return an immutable set of any additional profiles in use.
|
Set<Object> |
getAllSources()
Return an immutable set of all the sources that will be added to an
ApplicationContext when
run(String...) is called. |
protected Log |
getApplicationLog()
Returns the
Log for the application. |
ApplicationStartup |
getApplicationStartup()
Returns the
ApplicationStartup used for collecting startup metrics. |
ClassLoader |
getClassLoader()
Either the ClassLoader that will be used in the ApplicationContext (if
resourceLoader is set, or the context
class loader (if not null), or the loader of the Spring ClassUtils class. |
String |
getEnvironmentPrefix()
Return a prefix that should be applied when obtaining configuration properties from
the system environment.
|
Set<ApplicationContextInitializer<?>> |
getInitializers()
Returns read-only ordered Set of the
ApplicationContextInitializer s that
will be applied to the Spring ApplicationContext . |
Set<ApplicationListener<?>> |
getListeners()
Returns read-only ordered Set of the
ApplicationListener s that will be
applied to the SpringApplication and registered with the ApplicationContext
. |
Class<?> |
getMainApplicationClass()
Returns the main application class that has been deduced or explicitly configured.
|
ResourceLoader |
getResourceLoader()
The ResourceLoader that will be used in the ApplicationContext.
|
static SpringApplicationShutdownHandlers |
getShutdownHandlers()
Return a
SpringApplicationShutdownHandlers instance that can be used to add
or remove handlers that perform actions before the JVM is shutdown. |
Set<String> |
getSources()
Returns a mutable set of the sources that will be added to an ApplicationContext
when
run(String...) is called. |
WebApplicationType |
getWebApplicationType()
Returns the type of web application that is being run.
|
protected void |
load(ApplicationContext context,
Object[] sources)
Load beans into the application context.
|
protected void |
logStartupInfo(boolean isRoot)
Called to log startup information, subclasses may override to add additional
logging.
|
protected void |
logStartupProfileInfo(ConfigurableApplicationContext context)
Called to log active profile information.
|
static void |
main(String[] args)
A basic main that can be used to launch an application.
|
protected void |
postProcessApplicationContext(ConfigurableApplicationContext context)
Apply any relevant post processing the
ApplicationContext . |
protected void |
refresh(ConfigurableApplicationContext applicationContext)
Refresh the underlying
ApplicationContext . |
protected void |
registerLoggedException(Throwable exception)
Register that the given exception has been logged.
|
static ConfigurableApplicationContext |
run(Class<?>[] primarySources,
String[] args)
Static helper that can be used to run a
SpringApplication from the
specified sources using default settings and user supplied arguments. |
static ConfigurableApplicationContext |
run(Class<?> primarySource,
String... args)
Static helper that can be used to run a
SpringApplication from the
specified source using default settings. |
ConfigurableApplicationContext |
run(String... args)
Run the Spring application, creating and refreshing a new
ApplicationContext . |
void |
setAddCommandLineProperties(boolean addCommandLineProperties)
Sets if a
CommandLinePropertySource should be added to the application
context in order to expose arguments. |
void |
setAddConversionService(boolean addConversionService)
Sets if the
ApplicationConversionService should be added to the application
context's Environment . |
void |
setAdditionalProfiles(String... profiles)
Set additional profile values to use (on top of those set in system or command line
properties).
|
void |
setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding)
Sets if bean definition overriding, by registering a definition with the same name
as an existing definition, should be allowed.
|
void |
setApplicationContextClass(Class<? extends ConfigurableApplicationContext> applicationContextClass)
Deprecated.
since 2.4.0 for removal in 2.6.0 in favor of
setApplicationContextFactory(ApplicationContextFactory) |
void |
setApplicationContextFactory(ApplicationContextFactory applicationContextFactory)
Sets the factory that will be called to create the application context.
|
void |
setApplicationStartup(ApplicationStartup applicationStartup)
Set the
ApplicationStartup to use for collecting startup metrics. |
void |
setBanner(Banner banner)
Sets the
Banner instance which will be used to print the banner when no
static banner file is provided. |
void |
setBannerMode(Banner.Mode bannerMode)
Sets the mode used to display the banner when the application runs.
|
void |
setBeanNameGenerator(BeanNameGenerator beanNameGenerator)
Sets the bean name generator that should be used when generating bean names.
|
void |
setDefaultProperties(Map<String,Object> defaultProperties)
Set default environment properties which will be used in addition to those in the
existing
Environment . |
void |
setDefaultProperties(Properties defaultProperties)
Convenient alternative to
setDefaultProperties(Map) . |
void |
setEnvironment(ConfigurableEnvironment environment)
Sets the underlying environment that should be used with the created application
context.
|
void |
setEnvironmentPrefix(String environmentPrefix)
Set the prefix that should be applied when obtaining configuration properties from
the system environment.
|
void |
setHeadless(boolean headless)
Sets if the application is headless and should not instantiate AWT.
|
void |
setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers)
Sets the
ApplicationContextInitializer that will be applied to the Spring
ApplicationContext . |
void |
setLazyInitialization(boolean lazyInitialization)
Sets if beans should be initialized lazily.
|
void |
setListeners(Collection<? extends ApplicationListener<?>> listeners)
Sets the
ApplicationListener s that will be applied to the SpringApplication
and registered with the ApplicationContext . |
void |
setLogStartupInfo(boolean logStartupInfo)
Sets if the application information should be logged when the application starts.
|
void |
setMainApplicationClass(Class<?> mainApplicationClass)
Set a specific main application class that will be used as a log source and to
obtain version information.
|
void |
setRegisterShutdownHook(boolean registerShutdownHook)
Sets if the created
ApplicationContext should have a shutdown hook
registered. |
void |
setResourceLoader(ResourceLoader resourceLoader)
Sets the
ResourceLoader that should be used when loading resources. |
void |
setSources(Set<String> sources)
Set additional sources that will be used to create an ApplicationContext.
|
void |
setWebApplicationType(WebApplicationType webApplicationType)
Sets the type of web application to be run.
|
@Deprecated public static final String DEFAULT_CONTEXT_CLASS
ApplicationContextFactory
@Deprecated public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS
ApplicationContextFactory
@Deprecated public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS
ApplicationContextFactory
public static final String BANNER_LOCATION_PROPERTY_VALUE
public static final String BANNER_LOCATION_PROPERTY
public SpringApplication(Class<?>... primarySources)
SpringApplication
instance. The application context will load
beans from the specified primary sources (see class-level
documentation for details. The instance can be customized before calling
run(String...)
.primarySources
- the primary bean sourcesrun(Class, String[])
,
SpringApplication(ResourceLoader, Class...)
,
setSources(Set)
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources)
SpringApplication
instance. The application context will load
beans from the specified primary sources (see class-level
documentation for details. The instance can be customized before calling
run(String...)
.resourceLoader
- the resource loader to useprimarySources
- the primary bean sourcesrun(Class, String[])
,
setSources(Set)
public ConfigurableApplicationContext run(String... args)
ApplicationContext
.args
- the application arguments (usually passed from a Java main method)ApplicationContext
@Deprecated public StandardEnvironment convertEnvironment(ConfigurableEnvironment environment)
environment
to an application
environment that doesn't attempt to resolve profile properties directly.environment
- the environment to convertprotected void configureEnvironment(ConfigurableEnvironment environment, String[] args)
configurePropertySources(ConfigurableEnvironment, String[])
and
configureProfiles(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.environment
- this application's environmentargs
- arguments passed to the run
methodconfigureProfiles(ConfigurableEnvironment, String[])
,
configurePropertySources(ConfigurableEnvironment, String[])
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args)
PropertySource
s in this application's
environment.environment
- this application's environmentargs
- arguments passed to the run
methodconfigureEnvironment(ConfigurableEnvironment, String[])
protected void configureProfiles(ConfigurableEnvironment environment, String[] args)
spring.profiles.active
property.environment
- this application's environmentargs
- arguments passed to the run
methodconfigureEnvironment(ConfigurableEnvironment, String[])
,
ConfigFileApplicationListener
protected void bindToSpringApplication(ConfigurableEnvironment environment)
SpringApplication
.environment
- the environment to bindprotected ConfigurableApplicationContext createApplicationContext()
ApplicationContext
. By default this
method will respect any explicitly set application context class or factory before
falling back to a suitable default.setApplicationContextClass(Class)
,
setApplicationContextFactory(ApplicationContextFactory)
protected void postProcessApplicationContext(ConfigurableApplicationContext context)
ApplicationContext
. Subclasses can
apply additional processing as required.context
- the application contextprotected void applyInitializers(ConfigurableApplicationContext context)
ApplicationContextInitializer
s to the context before it is
refreshed.context
- the configured ApplicationContext (not refreshed yet)ConfigurableApplicationContext.refresh()
protected void logStartupInfo(boolean isRoot)
isRoot
- true if this application is the root of a context hierarchyprotected void logStartupProfileInfo(ConfigurableApplicationContext context)
context
- the application contextprotected Log getApplicationLog()
Log
for the application. By default will be deduced.protected void load(ApplicationContext context, Object[] sources)
context
- the context to load beans intosources
- the sources to loadpublic ResourceLoader getResourceLoader()
public ClassLoader getClassLoader()
resourceLoader
is set, or the context
class loader (if not null), or the loader of the Spring ClassUtils
class.protected org.springframework.boot.BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources)
BeanDefinitionLoader
.registry
- the bean definition registrysources
- the sources to loadBeanDefinitionLoader
that will be used to load beansprotected void refresh(ConfigurableApplicationContext applicationContext)
ApplicationContext
.applicationContext
- the application context to refreshprotected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args)
context
- the application contextargs
- the application argumentsprotected void registerLoggedException(Throwable exception)
exception
- the exception that was loggedpublic Class<?> getMainApplicationClass()
null
public void setMainApplicationClass(Class<?> mainApplicationClass)
null
if there is no explicit application class.mainApplicationClass
- the mainApplicationClass to set or null
public WebApplicationType getWebApplicationType()
public void setWebApplicationType(WebApplicationType webApplicationType)
webApplicationType
- the web application typepublic void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding)
false
.allowBeanDefinitionOverriding
- if overriding is allowedDefaultListableBeanFactory.setAllowBeanDefinitionOverriding(boolean)
public void setLazyInitialization(boolean lazyInitialization)
false
.lazyInitialization
- if initialization should be lazyBeanDefinition.setLazyInit(boolean)
public void setHeadless(boolean headless)
true
to prevent java icons appearing.headless
- if the application is headlesspublic void setRegisterShutdownHook(boolean registerShutdownHook)
ApplicationContext
should have a shutdown hook
registered. Defaults to true
to ensure that JVM shutdowns are handled
gracefully.registerShutdownHook
- if the shutdown hook should be registeredgetShutdownHandlers()
public void setBanner(Banner banner)
Banner
instance which will be used to print the banner when no
static banner file is provided.banner
- the Banner instance to usepublic void setBannerMode(Banner.Mode bannerMode)
Banner.Mode.CONSOLE
.bannerMode
- the mode used to display the bannerpublic void setLogStartupInfo(boolean logStartupInfo)
true
.logStartupInfo
- if startup info should be logged.public void setAddCommandLineProperties(boolean addCommandLineProperties)
CommandLinePropertySource
should be added to the application
context in order to expose arguments. Defaults to true
.addCommandLineProperties
- if command line arguments should be exposedpublic void setAddConversionService(boolean addConversionService)
ApplicationConversionService
should be added to the application
context's Environment
.addConversionService
- if the application conversion service should be added@Deprecated public void addBootstrapper(Bootstrapper bootstrapper)
addBootstrapRegistryInitializer(BootstrapRegistryInitializer)
Bootstrapper
that can be used to initialize the
BootstrapRegistry
.bootstrapper
- the bootstraperpublic void addBootstrapRegistryInitializer(BootstrapRegistryInitializer bootstrapRegistryInitializer)
BootstrapRegistryInitializer
instances that can be used to initialize
the BootstrapRegistry
.bootstrapRegistryInitializer
- the bootstrap registry initializer to addpublic void setDefaultProperties(Map<String,Object> defaultProperties)
Environment
.defaultProperties
- the additional properties to setpublic void setDefaultProperties(Properties defaultProperties)
setDefaultProperties(Map)
.defaultProperties
- some Properties
public void setAdditionalProfiles(String... profiles)
profiles
- the additional profiles to setpublic Set<String> getAdditionalProfiles()
public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator)
beanNameGenerator
- the bean name generatorpublic void setEnvironment(ConfigurableEnvironment environment)
environment
- the environmentpublic void addPrimarySources(Collection<Class<?>> additionalPrimarySources)
run(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.
additionalPrimarySources
- the additional primary sources to addSpringApplication(Class...)
,
getSources()
,
setSources(Set)
,
getAllSources()
public Set<String> getSources()
run(String...)
is called.
Sources set here will be used in addition to any primary sources set in the constructor.
SpringApplication(Class...)
,
getAllSources()
public void setSources(Set<String> sources)
Sources set here will be used in addition to any primary sources set in the constructor.
sources
- the application sources to setSpringApplication(Class...)
,
getAllSources()
public Set<Object> getAllSources()
run(String...)
is called. This method combines any
primary sources specified in the constructor with any additional ones that have
been explicitly set
.public void setResourceLoader(ResourceLoader resourceLoader)
ResourceLoader
that should be used when loading resources.resourceLoader
- the resource loaderpublic String getEnvironmentPrefix()
public void setEnvironmentPrefix(String environmentPrefix)
environmentPrefix
- the environment property prefix to set@Deprecated public void setApplicationContextClass(Class<? extends ConfigurableApplicationContext> applicationContextClass)
setApplicationContextFactory(ApplicationContextFactory)
ApplicationContext
that will be created. If not
specified defaults to DEFAULT_SERVLET_WEB_CONTEXT_CLASS
for web based
applications or AnnotationConfigApplicationContext
for non web based
applications.applicationContextClass
- the context class to setpublic void setApplicationContextFactory(ApplicationContextFactory applicationContextFactory)
AnnotationConfigServletWebServerApplicationContext
for servlet web
applications, AnnotationConfigReactiveWebServerApplicationContext
for
reactive web applications, and AnnotationConfigApplicationContext
for
non-web applications.applicationContextFactory
- the factory for the contextpublic void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers)
ApplicationContextInitializer
that will be applied to the Spring
ApplicationContext
.initializers
- the initializers to setpublic void addInitializers(ApplicationContextInitializer<?>... initializers)
ApplicationContextInitializer
s to be applied to the Spring
ApplicationContext
.initializers
- the initializers to addpublic Set<ApplicationContextInitializer<?>> getInitializers()
ApplicationContextInitializer
s that
will be applied to the Spring ApplicationContext
.public void setListeners(Collection<? extends ApplicationListener<?>> listeners)
ApplicationListener
s that will be applied to the SpringApplication
and registered with the ApplicationContext
.listeners
- the listeners to setpublic void addListeners(ApplicationListener<?>... listeners)
ApplicationListener
s to be applied to the SpringApplication and
registered with the ApplicationContext
.listeners
- the listeners to addpublic Set<ApplicationListener<?>> getListeners()
ApplicationListener
s that will be
applied to the SpringApplication and registered with the ApplicationContext
.public void setApplicationStartup(ApplicationStartup applicationStartup)
ApplicationStartup
to use for collecting startup metrics.applicationStartup
- the application startup to usepublic ApplicationStartup getApplicationStartup()
ApplicationStartup
used for collecting startup metrics.public static SpringApplicationShutdownHandlers getShutdownHandlers()
SpringApplicationShutdownHandlers
instance that can be used to add
or remove handlers that perform actions before the JVM is shutdown.SpringApplicationShutdownHandlers
instancepublic static ConfigurableApplicationContext run(Class<?> primarySource, String... args)
SpringApplication
from the
specified source using default settings.primarySource
- the primary source to loadargs
- the application arguments (usually passed from a Java main method)ApplicationContext
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args)
SpringApplication
from the
specified sources using default settings and user supplied arguments.primarySources
- the primary sources to loadargs
- the application arguments (usually passed from a Java main method)ApplicationContext
public static void main(String[] args) throws Exception
Most developers will want to define their own main method and call the
run
method instead.
args
- command line argumentsException
- if the application cannot be startedrun(Class[], String[])
,
run(Class, String...)
public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators)
SpringApplication
and obtain a
code indicating success (0) or otherwise. Does not throw exceptions but should
print stack traces of any encountered. Applies the specified
ExitCodeGenerator
in addition to any Spring beans that implement
ExitCodeGenerator
. In the case of multiple exit codes the highest value
will be used (or if all values are negative, the lowest value will be used)context
- the context to close if possibleexitCodeGenerators
- exit code generators