22. SpringApplication

The SpringApplication class provides a convenient way to bootstrap a Spring application that will be started from a main() method. In many situations you can just delegate to the static SpringApplication.run method:

public static void main(String[] args) {
    SpringApplication.run(MySpringConfiguration.class, args);
}

When your application starts you should see something similar to the following:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::   v1.2.3.RELEASE

2013-07-31 00:08:16.117  INFO 56603 --- [           main] o.s.b.s.app.SampleApplication            : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)
2013-07-31 00:08:16.166  INFO 56603 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
2014-03-04 13:09:54.912  INFO 41370 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-03-04 13:09:56.501  INFO 41370 --- [           main] o.s.b.s.app.SampleApplication            : Started SampleApplication in 2.992 seconds (JVM running for 3.658)

By default INFO logging messages will be shown, including some relevant startup details such as the user that launched the application.

22.1 Customizing the Banner

The banner that is printed on start up can be changed by adding a banner.txt file to your classpath, or by setting banner.location to the location of such a file. If the file has an unusual encoding you can set banner.encoding (default is UTF-8).

You can use the following variables inside your banner.txt file:

Table 22.1. Banner variables

VariableDescription

${application.version}

The version number of your application as declared in MANIFEST.MF. For example 1.0.

${application.formatted-version}

The version number of your application as declared in MANIFEST.MF formatted for display (surrounded with brackets and prefixed with v). For example (v1.0).

${spring-boot.version}

The Spring Boot version that you are using. For example 1.2.3.RELEASE.

${spring-boot.formatted-version}

The Spring Boot version that you are using formatted for display (surrounded with brackets and prefixed with v). For example (v1.2.3.RELEASE).


[Tip]Tip

The SpringBootApplication.setBanner(…​) method can be used if you want to generate a banner programmatically. Use the org.springframework.boot.Banner interface and implement your own printBanner() method.

22.2 Customizing SpringApplication

If the SpringApplication defaults aren’t to your taste you can instead create a local instance and customize it. For example, to turn off the banner you would write:

public static void main(String[] args) {
    SpringApplication app = new SpringApplication(MySpringConfiguration.class);
    app.setShowBanner(false);
    app.run(args);
}
[Note]Note

The constructor arguments passed to SpringApplication are configuration sources for spring beans. In most cases these will be references to @Configuration classes, but they could also be references to XML configuration or to packages that should be scanned.

It is also possible to configure the SpringApplication using an application.properties file. See Chapter 23, Externalized Configuration for details.

For a complete list of the configuration options, see the SpringApplication Javadoc.

22.3 Fluent builder API

If you need to build an ApplicationContext hierarchy (multiple contexts with a parent/child relationship), or if you just prefer using a ‘fluent’ builder API, you can use the SpringApplicationBuilder.

The SpringApplicationBuilder allows you to chain together multiple method calls, and includes parent and child methods that allow you to create a hierarchy.

For example:

new SpringApplicationBuilder()
    .showBanner(false)
    .sources(Parent.class)
    .child(Application.class)
    .run(args);
[Note]Note

There are some restrictions when creating an ApplicationContext hierarchy, e.g. Web components must be contained within the child context, and the same Environment will be used for both parent and child contexts. See the SpringApplicationBuilder Javadoc for full details.

22.4 Application events and listeners

In addition to the usual Spring Framework events, such as ContextRefreshedEvent, a SpringApplication sends some additional application events. Some events are actually triggered before the ApplicationContext is created.

You can register event listeners in a number of ways, the most common being SpringApplication.addListeners(…​) method.

Application events are sent in the following order, as your application runs:

  1. An ApplicationStartedEvent is sent at the start of a run, but before any processing except the registration of listeners and initializers.
  2. An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created.
  3. An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.
  4. An ApplicationFailedEvent is sent if there is an exception on startup.
[Tip]Tip

You often won’t need to use application events, but it can be handy to know that they exist. Internally, Spring Boot uses events to handle a variety of tasks.

22.5 Web environment

A SpringApplication will attempt to create the right type of ApplicationContext on your behalf. By default, an AnnotationConfigApplicationContext or AnnotationConfigEmbeddedWebApplicationContext will be used, depending on whether you are developing a web application or not.

The algorithm used to determine a ‘web environment’ is fairly simplistic (based on the presence of a few classes). You can use setWebEnvironment(boolean webEnvironment) if you need to override the default.

It is also possible to take complete control of the ApplicationContext type that will be used by calling setApplicationContextClass(…​).

[Tip]Tip

It is often desirable to call setWebEnvironment(false) when using SpringApplication within a JUnit test.

22.6 Using the CommandLineRunner

If you want access to the raw command line arguments, or you need to run some specific code once the SpringApplication has started you can implement the CommandLineRunner interface. The run(String…​ args) method will be called on all Spring beans implementing this interface.

import org.springframework.boot.*
import org.springframework.stereotype.*

@Component
public class MyBean implements CommandLineRunner {

    public void run(String... args) {
        // Do something...
    }

}

You can additionally implement the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation if several CommandLineRunner beans are defined that must be called in a specific order.

22.7 Application exit

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when the application ends.