I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

Spring Boot can do a lot of things; in this tutorial, we’re going to go over a few of the more interesting configuration options in Boot.

Further reading:

Migrating from Spring to Spring Boot

See how to properly migrate from a Spring to Spring Boot.

Read more

Creating a Custom Starter with Spring Boot

A quick and practical guide to creating custom Spring Boot starters.

Read more

Testing in Spring Boot

Learn about how the Spring Boot supports testing, to write unit tests efficiently.

Read more

2. The Port Number

In main standalone applications, the main HTTP port defaults to 8080; we can easily configure Boot to use a different port:

server.port=8083

And for, YAML-based configuration:

server:
    port: 8083

We can also programmatically customize the server port:

@Component
public class CustomizationBean implements
  WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
 
    @Override
    public void customize(ConfigurableServletWebServerFactory container) {
        container.setPort(8083);
    }
}

3. The Context Path

By default, the context path is “/”. If that’s not ideal and you need to change it – to something like /app_name, here’s the quick and simple way to do it via properties:

server.servlet.contextPath=/springbootapp

And for YAML-based configuration:

server:
    servlet:
        contextPath:/springbootapp

Finally – the change can be done programmatically as well:

@Component
public class CustomizationBean
  implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
 
    @Override
    public void customize(ConfigurableServletWebServerFactorycontainer) {
        container.setContextPath("/springbootapp");
    }
}

4. The White Label Error Page

Spring Boot automatically registers a BasicErrorController bean if you don’t specify any custom implementation in the configuration.

However, this default controller can, of course, be configured:

public class MyCustomErrorController implements ErrorController {
 
    private static final String PATH = "/error";
    
    @GetMapping(value=PATH)
    public String error() {
        return "Error haven";
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

5. Customize The Error Messages

Boot provides /error mappings by default to handle errors in a sensible way.

If you want to configure more specific error pages, there’s good support for a uniform Java DSL to customize error handling:

@Component
public class CustomizationBean
  implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
 
    @Override
    public void customize(ConfigurableServletWebServerFactorycontainer) {        
        container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
        container.addErrorPages(new ErrorPage("/errorHaven"));
    }
}

Here, we specifically handled Bad Request to match the /400 path and all others to match the common path.

And a very simple /errorHaven implementation:

@GetMapping("/errorHaven")
String errorHeaven() {
    return "You have reached the haven of errors!!!";
}

Output:

You have reached the haven of errors!!!

6. Shut Down A Boot Application Programmatically

You can programmatically shut down a Boot app with the help of SpringApplication. This has a static exit() method that takes two arguments: the ApplicationContext and an ExitCodeGenerator:

@Autowired
public void shutDown(ExecutorServiceExitCodeGenerator exitCodeGenerator) {
    SpringApplication.exit(applicationContext, exitCodeGenerator);
}

It’s through this utility method that we can shut down the app.

7. Configure the Logging Levels

You can easily tune the logging levels in a Boot application; Starting with version 1.2.0 onwards, you can configure the log level in the main properties file:

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR

And just as with a standard Spring app – you can activate different logging systems like Logback, log4j, log4j2, etc by adding their customized XML or properties file in the classpath and defining the libraries in the pom.

8. Register a New Servlet

If you’re deploying the application with the help of the embedded server, you can register new Servlets in a Boot application by exposing them as beans from conventional config:

@Bean
public HelloWorldServlet helloWorld() {
    return new HelloWorldServlet();
}

Alternatively, you can use a ServletRegistrationBean:

@Bean
public SpringHelloServletRegistrationBean servletRegistrationBean() {
 
    SpringHelloServletRegistrationBean bean = new SpringHelloServletRegistrationBean(
      new SpringHelloWorldServlet(), "/springHelloWorld/*");
    bean.setLoadOnStartup(1);
    bean.addInitParameter("message", "SpringHelloWorldServlet special message");
    return bean;
}

9. Configure Jetty or Undertow in Boot Application

The Spring Boot starters generally use Tomcat as the default embedded server. If that needs to be changed – you can exclude the Tomcat dependency and include Jetty or Undertow instead:

Configuring Jetty

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
@Bean
public JettyEmbeddedServletContainerFactory  jettyEmbeddedServletContainerFactory() {
    JettyEmbeddedServletContainerFactory jettyContainer = 
      new JettyEmbeddedServletContainerFactory();
    
    jettyContainer.setPort(9000);
    jettyContainer.setContextPath("/springbootapp");
    return jettyContainer;
}

Configuring Undertow

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
@Bean
public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
    UndertowEmbeddedServletContainerFactory factory = 
      new UndertowEmbeddedServletContainerFactory();
    
    factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
        @Override
        public void customize(io.undertow.Undertow.Builder builder) {
            builder.addHttpListener(8080, "0.0.0.0");
        }
    });
    
    return factory;
}

10. Conclusion

In this quick article, we went over some of the more interesting and useful Spring Boot configuration options.

There are of course many, many more options to configure and tune a Boot app to your needs in the reference docs – these are just some of the more useful I found.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
mtbadi39
Guest
mtbadi39

Hi;
its greate , filicitations !
How about i18n , message bundle and static resources ?
i know there is a lot in spring docs, forums or by googling but i just like your way.
many thanks.

Eugen Paraschiv
Guest

Yes, Spring Boot as a host of very cool features and options for configuration – these are just a few of the more common and useful ones, but certainly not a replacement for the standard reference. That being said – I might write another article about these – as they do come up often enough. Thanks for the suggestion. Cheers,
Eugen.

reddynr
Guest
reddynr

HI,
Nice Example.Thanks

I have a requirement to to load applicationContext based on countryCode. here is applicationContext-local.properties, Expected implementation applicationContext-local_MX.properties

Any advice, much appreciated.

Grzegorz Piwowarek
Guest
Grzegorz Piwowarek

Are you sure you are looking for right solutions? Maybe you do not need to reload the whole context but only some beans? In this case you might be looking for Spring profiles. http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/boot-features-profiles.html Let me know if this is what you were looking for

Eugen Paraschiv
Guest

Hey Reddynr,
Unfortunately I’ve never tried to do that, so I’m not sure if it’s something the framework supports. Cheers,
Eugen.

reddynr
Guest
reddynr

Thanks Eugen Paraschiv.

Configured beans for country specfic differenciate by id=”beanname_coutrycode” and used same bean for all the senerios. works fine.

Danilo Gomes
Guest
Danilo Gomes

Hi, Eugen, how are you?

Congratulations for the article.
Your posts are always clear and objective but without forget the main details.

The text is 99% good. I guess there is a misspelling at “io.undertow.Undertow.Builde” (missing “r”) then it’ll become 100% good.

Best.

Grzegorz Piwowarek
Guest
Grzegorz Piwowarek

Oh, “r” got eaten somehow 🙂 thanks!