类 SpringApplication


  • public class SpringApplication
    extends Object
    Classes 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 ApplicationContext instance (depending on your classpath)
    • Register a CommandLinePropertySource to expose command line arguments as Spring properties
    • Refresh the application context, loading all singleton beans
    • Trigger any CommandLineRunner beans
    In most circumstances the static run(Object, 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) throws Exception {
         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) throws Exception {
       SpringApplication app = new SpringApplication(MyApplication.class);
       // ... customize app settings here
       app.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, any of the following sources can also be used:
    • Class - A Java class to be loaded by AnnotatedBeanDefinitionReader
    • Resource - An XML resource to be loaded by XmlBeanDefinitionReader, or a groovy script to be loaded by GroovyBeanDefinitionReader
    • Package - A Java package to be scanned by ClassPathBeanDefinitionScanner
    • CharSequence - A class name, resource handle or package name to loaded as appropriate. If the CharSequence cannot be resolved to class and does not resolve to a Resource that exists it will be considered a Package.
    另请参阅:
    run(Object, String[]), run(Object[], String[]), SpringApplication(Object...)
    • 方法概要

      所有方法 静态方法 实例方法 具体方法 
      修饰符和类型方法说明
      voidaddInitializers​(org.springframework.context.ApplicationContextInitializer<?>... initializers)
      Add ApplicationContextInitializers to be applied to the Spring ApplicationContext.
      voidaddListeners​(org.springframework.context.ApplicationListener<?>... listeners)
      Add ApplicationListeners to be applied to the SpringApplication and registered with the ApplicationContext.
      protected voidafterRefresh​(org.springframework.context.ConfigurableApplicationContext context, ApplicationArguments args)
      Called after the context has been refreshed.
      protected voidapplyInitializers​(org.springframework.context.ConfigurableApplicationContext context)
      Apply any ApplicationContextInitializers to the context before it is refreshed.
      protected voidconfigureEnvironment​(org.springframework.core.env.ConfigurableEnvironment environment, String[] args)
      protected voidconfigureProfiles​(org.springframework.core.env.ConfigurableEnvironment environment, String[] args)
      Configure which profiles are active (or active by default) for this application environment.
      protected voidconfigurePropertySources​(org.springframework.core.env.ConfigurableEnvironment environment, String[] args)
      Add, remove or re-order any PropertySources in this application's environment.
      protected org.springframework.context.ConfigurableApplicationContextcreateApplicationContext()
      Strategy method used to create the ApplicationContext.
      protected org.springframework.boot.BeanDefinitionLoadercreateBeanDefinitionLoader​(org.springframework.beans.factory.support.BeanDefinitionRegistry registry, Object[] sources)
      Factory method used to create the BeanDefinitionLoader.
      static intexit​(org.springframework.context.ApplicationContext context, ExitCodeGenerator... exitCodeGenerators)
      Static helper that can be used to exit a SpringApplication and obtain a code indicating success (0) or otherwise.
      protected org.apache.commons.logging.LoggetApplicationLog()
      Returns the Log for the application.
      ClassLoadergetClassLoader()
      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.
      Set<org.springframework.context.ApplicationContextInitializer<?>>getInitializers()
      Returns read-only ordered Set of the ApplicationContextInitializers that will be applied to the Spring ApplicationContext.
      Set<org.springframework.context.ApplicationListener<?>>getListeners()
      Returns read-only ordered Set of the ApplicationListeners 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.
      org.springframework.core.io.ResourceLoadergetResourceLoader()
      The ResourceLoader that will be used in the ApplicationContext.
      Set<Object>getSources()
      Returns a mutable set of the sources that will be added to an ApplicationContext when run(String...) is called.
      booleanisWebEnvironment()
      Returns whether this SpringApplication is running within a web environment.
      protected voidload​(org.springframework.context.ApplicationContext context, Object[] sources)
      Load beans into the application context.
      protected voidlogStartupInfo​(boolean isRoot)
      Called to log startup information, subclasses may override to add additional logging.
      protected voidlogStartupProfileInfo​(org.springframework.context.ConfigurableApplicationContext context)
      Called to log active profile information.
      static voidmain​(String[] args)
      A basic main that can be used to launch an application.
      protected voidpostProcessApplicationContext​(org.springframework.context.ConfigurableApplicationContext context)
      Apply any relevant post processing the ApplicationContext.
      protected voidrefresh​(org.springframework.context.ApplicationContext applicationContext)
      Refresh the underlying ApplicationContext.
      protected voidregisterLoggedException​(Throwable exception)
      Register that the given exception has been logged.
      static org.springframework.context.ConfigurableApplicationContextrun​(Object[] sources, String[] args)
      Static helper that can be used to run a SpringApplication from the specified sources using default settings and user supplied arguments.
      static org.springframework.context.ConfigurableApplicationContextrun​(Object source, String... args)
      Static helper that can be used to run a SpringApplication from the specified source using default settings.
      org.springframework.context.ConfigurableApplicationContextrun​(String... args)
      Run the Spring application, creating and refreshing a new ApplicationContext.
      voidsetAddCommandLineProperties​(boolean addCommandLineProperties)
      Sets if a CommandLinePropertySource should be added to the application context in order to expose arguments.
      voidsetAdditionalProfiles​(String... profiles)
      Set additional profile values to use (on top of those set in system or command line properties).
      voidsetApplicationContextClass​(Class<? extends org.springframework.context.ConfigurableApplicationContext> applicationContextClass)
      Sets the type of Spring ApplicationContext that will be created.
      voidsetBanner​(Banner banner)
      Sets the Banner instance 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​(org.springframework.beans.factory.support.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 existing Environment.
      voidsetDefaultProperties​(Properties defaultProperties)
      Convenient alternative to setDefaultProperties(Map).
      voidsetEnvironment​(org.springframework.core.env.ConfigurableEnvironment environment)
      Sets the underlying environment that should be used with the created application context.
      voidsetHeadless​(boolean headless)
      Sets if the application is headless and should not instantiate AWT.
      voidsetInitializers​(Collection<? extends org.springframework.context.ApplicationContextInitializer<?>> initializers)
      Sets the ApplicationContextInitializer that will be applied to the Spring ApplicationContext.
      voidsetListeners​(Collection<? extends org.springframework.context.ApplicationListener<?>> listeners)
      Sets the ApplicationListeners that will be applied to the SpringApplication and registered with the ApplicationContext.
      voidsetLogStartupInfo​(boolean logStartupInfo)
      Sets if the application information should be logged when the application starts.
      voidsetMainApplicationClass​(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 created ApplicationContext should have a shutdown hook registered.
      voidsetResourceLoader​(org.springframework.core.io.ResourceLoader resourceLoader)
      Sets the ResourceLoader that should be used when loading resources.
      voidsetSources​(Set<Object> sources)
      The sources that will be used to create an ApplicationContext.
      voidsetWebEnvironment​(boolean webEnvironment)
      Sets if this application is running within a web environment.
    • 方法详细资料

      • run

        public org.springframework.context.ConfigurableApplicationContext run​(String... args)
        Run the Spring application, creating and refreshing a new ApplicationContext.
        参数:
        args - the application arguments (usually passed from a Java main method)
        返回:
        a running ApplicationContext
      • configureProfiles

        protected void configureProfiles​(org.springframework.core.env.ConfigurableEnvironment environment,
                                         String[] args)
        Configure which profiles are active (or active by default) for this application environment. Additional profiles may be activated during configuration file processing via the spring.profiles.active property.
        参数:
        environment - this application's environment
        args - arguments passed to the run method
        另请参阅:
        configureEnvironment(ConfigurableEnvironment, String[]), ConfigFileApplicationListener
      • createApplicationContext

        protected org.springframework.context.ConfigurableApplicationContext createApplicationContext()
        Strategy method used to create the ApplicationContext. By default this method will respect any explicitly set application context or application context class before falling back to a suitable default.
        返回:
        the application context (not yet refreshed)
        另请参阅:
        setApplicationContextClass(Class)
      • postProcessApplicationContext

        protected void postProcessApplicationContext​(org.springframework.context.ConfigurableApplicationContext context)
        Apply any relevant post processing the ApplicationContext. Subclasses can apply additional processing as required.
        参数:
        context - the application context
      • applyInitializers

        protected void applyInitializers​(org.springframework.context.ConfigurableApplicationContext context)
        Apply any ApplicationContextInitializers to the context before it is refreshed.
        参数:
        context - the configured ApplicationContext (not refreshed yet)
        另请参阅:
        ConfigurableApplicationContext.refresh()
      • logStartupInfo

        protected void logStartupInfo​(boolean isRoot)
        Called to log startup information, subclasses may override to add additional logging.
        参数:
        isRoot - true if this application is the root of a context hierarchy
      • logStartupProfileInfo

        protected void logStartupProfileInfo​(org.springframework.context.ConfigurableApplicationContext context)
        Called to log active profile information.
        参数:
        context - the application context
      • getApplicationLog

        protected org.apache.commons.logging.Log getApplicationLog()
        Returns the Log for the application. By default will be deduced.
        返回:
        the application log
      • load

        protected void load​(org.springframework.context.ApplicationContext context,
                            Object[] sources)
        Load beans into the application context.
        参数:
        context - the context to load beans into
        sources - the sources to load
      • getResourceLoader

        public org.springframework.core.io.ResourceLoader getResourceLoader()
        The ResourceLoader that will be used in the ApplicationContext.
        返回:
        the resourceLoader the resource loader that will be used in the ApplicationContext (or null if the default)
      • getClassLoader

        public 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.
        返回:
        a ClassLoader (never null)
      • createBeanDefinitionLoader

        protected org.springframework.boot.BeanDefinitionLoader createBeanDefinitionLoader​(org.springframework.beans.factory.support.BeanDefinitionRegistry registry,
                                                                                           Object[] sources)
        Factory method used to create the BeanDefinitionLoader.
        参数:
        registry - the bean definition registry
        sources - the sources to load
        返回:
        the BeanDefinitionLoader that will be used to load beans
      • refresh

        protected void refresh​(org.springframework.context.ApplicationContext applicationContext)
        Refresh the underlying ApplicationContext.
        参数:
        applicationContext - the application context to refresh
      • afterRefresh

        protected void afterRefresh​(org.springframework.context.ConfigurableApplicationContext context,
                                    ApplicationArguments args)
        Called after the context has been refreshed.
        参数:
        context - the application context
        args - the application arguments
      • registerLoggedException

        protected void registerLoggedException​(Throwable exception)
        Register 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.
        参数:
        exception - the exception that was logged
      • getMainApplicationClass

        public Class<?> getMainApplicationClass()
        Returns the main application class that has been deduced or explicitly configured.
        返回:
        the main application class or null
      • setMainApplicationClass

        public void setMainApplicationClass​(Class<?> mainApplicationClass)
        Set 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 to null if there is no explicit application class.
        参数:
        mainApplicationClass - the mainApplicationClass to set or null
      • setWebEnvironment

        public void setWebEnvironment​(boolean webEnvironment)
        Sets if this application is running within a web environment. If not specified will attempt to deduce the environment based on the classpath.
        参数:
        webEnvironment - if the application is running in a web environment
      • setHeadless

        public void setHeadless​(boolean headless)
        Sets if the application is headless and should not instantiate AWT. Defaults to true to prevent java icons appearing.
        参数:
        headless - if the application is headless
      • setRegisterShutdownHook

        public void setRegisterShutdownHook​(boolean registerShutdownHook)
        Sets if the created 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 registered
      • setBanner

        public void setBanner​(Banner banner)
        Sets the Banner instance which will be used to print the banner when no static banner file is provided.
        参数:
        banner - The Banner instance to use
      • setBannerMode

        public void setBannerMode​(Banner.Mode bannerMode)
        Sets the mode used to display the banner when the application runs. Defaults to Banner.Mode.CONSOLE.
        参数:
        bannerMode - the mode used to display the banner
      • setLogStartupInfo

        public void setLogStartupInfo​(boolean logStartupInfo)
        Sets if the application information should be logged when the application starts. Defaults to true.
        参数:
        logStartupInfo - if startup info should be logged.
      • setAddCommandLineProperties

        public void setAddCommandLineProperties​(boolean addCommandLineProperties)
        Sets if a CommandLinePropertySource should be added to the application context in order to expose arguments. Defaults to true.
        参数:
        addCommandLineProperties - if command line arguments should be exposed
      • setDefaultProperties

        public void setDefaultProperties​(Map<String,​Object> defaultProperties)
        Set default environment properties which will be used in addition to those in the existing Environment.
        参数:
        defaultProperties - the additional properties to set
      • setAdditionalProfiles

        public void setAdditionalProfiles​(String... profiles)
        Set additional profile values to use (on top of those set in system or command line properties).
        参数:
        profiles - the additional profiles to set
      • setBeanNameGenerator

        public void setBeanNameGenerator​(org.springframework.beans.factory.support.BeanNameGenerator beanNameGenerator)
        Sets the bean name generator that should be used when generating bean names.
        参数:
        beanNameGenerator - the bean name generator
      • setEnvironment

        public void setEnvironment​(org.springframework.core.env.ConfigurableEnvironment environment)
        Sets the underlying environment that should be used with the created application context.
        参数:
        environment - the environment
      • setSources

        public void setSources​(Set<Object> sources)
        The sources that will be used to create an ApplicationContext. A valid source is one of: a class, class name, package, package name, or an XML resource location. Can also be set using constructors and static convenience methods (e.g. run(Object[], String[])).

        NOTE: sources defined here will be used in addition to any sources specified on construction.

        参数:
        sources - the sources to set
        另请参阅:
        SpringApplication(Object...)
      • setResourceLoader

        public void setResourceLoader​(org.springframework.core.io.ResourceLoader resourceLoader)
        Sets the ResourceLoader that should be used when loading resources.
        参数:
        resourceLoader - the resource loader
      • setApplicationContextClass

        public void setApplicationContextClass​(Class<? extends org.springframework.context.ConfigurableApplicationContext> applicationContextClass)
        Sets the type of Spring ApplicationContext that will be created. If not specified defaults to DEFAULT_WEB_CONTEXT_CLASS for web based applications or AnnotationConfigApplicationContext for non web based applications.
        参数:
        applicationContextClass - the context class to set
      • setInitializers

        public void setInitializers​(Collection<? extends org.springframework.context.ApplicationContextInitializer<?>> initializers)
        Sets the ApplicationContextInitializer that will be applied to the Spring ApplicationContext.
        参数:
        initializers - the initializers to set
      • addInitializers

        public void addInitializers​(org.springframework.context.ApplicationContextInitializer<?>... initializers)
        Add ApplicationContextInitializers to be applied to the Spring ApplicationContext.
        参数:
        initializers - the initializers to add
      • getInitializers

        public Set<org.springframework.context.ApplicationContextInitializer<?>> getInitializers()
        Returns read-only ordered Set of the ApplicationContextInitializers that will be applied to the Spring ApplicationContext.
        返回:
        the initializers
      • setListeners

        public void setListeners​(Collection<? extends org.springframework.context.ApplicationListener<?>> listeners)
        Sets the ApplicationListeners that will be applied to the SpringApplication and registered with the ApplicationContext.
        参数:
        listeners - the listeners to set
      • addListeners

        public void addListeners​(org.springframework.context.ApplicationListener<?>... listeners)
        Add ApplicationListeners to be applied to the SpringApplication and registered with the ApplicationContext.
        参数:
        listeners - the listeners to add
      • getListeners

        public Set<org.springframework.context.ApplicationListener<?>> getListeners()
        Returns read-only ordered Set of the ApplicationListeners that will be applied to the SpringApplication and registered with the ApplicationContext .
        返回:
        the listeners
      • run

        public static org.springframework.context.ConfigurableApplicationContext run​(Object source,
                                                                                     String... args)
        Static helper that can be used to run a SpringApplication from the specified source using default settings.
        参数:
        source - the source to load
        args - the application arguments (usually passed from a Java main method)
        返回:
        the running ApplicationContext
      • run

        public static org.springframework.context.ConfigurableApplicationContext run​(Object[] sources,
                                                                                     String[] args)
        Static helper that can be used to run a SpringApplication from the specified sources using default settings and user supplied arguments.
        参数:
        sources - the sources to load
        args - the application arguments (usually passed from a Java main method)
        返回:
        the running ApplicationContext
      • main

        public static void main​(String[] args)
                         throws Exception
        A basic main that can be used to launch an application. This method is useful when application sources are defined via a --spring.main.sources command line argument.

        Most developers will want to define their own main method and call the run method instead.

        参数:
        args - command line arguments
        抛出:
        Exception - if the application cannot be started
        另请参阅:
        run(Object[], String[]), run(Object, String...)
      • exit

        public static int exit​(org.springframework.context.ApplicationContext context,
                               ExitCodeGenerator... exitCodeGenerators)
        Static helper that can be used to exit a 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 possible
        exitCodeGenerators - exist code generators
        返回:
        the outcome (0 if successful)