Configure a Spring Boot Web Application – 配置一个Spring Boot网络应用程序

最后修改: 2015年 6月 3日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

Spring Boot可以做很多事情;在本教程中,我们将介绍Boot中几个比较有趣的配置选项。

2. The Port Number

2.端口号

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

在主要的独立应用程序中,主要的HTTP端口默认为8080;我们可以很容易地配置Boot以使用不同的端口

server.port=8083

And for, YAML-based configuration:

而对于,基于YAML的配置。

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

3.语境之路

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:

默认情况下,上下文路径是”/”。如果这不是很理想,你需要改变它–像/app_name,这里有一个快速而简单的方法,通过属性来做。

server.servlet.contextPath=/springbootapp

And for YAML-based configuration:

而对于基于YAML的配置。

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

4.白标错误页

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

如果你没有在配置中指定任何自定义实现,Spring Boot会自动注册一个BasicErrorControllerbean。

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";
    }
}

5. Customize the Error Messages

5.自定义错误信息

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

Boot默认提供/error mappings,以合理的方式处理错误。

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

如果你想配置更具体的错误页面,对统一的Java DSL有很好的支持,以定制错误处理。

@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.

在这里,我们特别处理了Bad Request,以匹配/400路径,并将所有其他路径匹配到公共路径。

And a very simple /errorHaven implementation:

还有一个非常简单的/errorHaven实现。

@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

6.以编程方式关闭一个启动应用程序

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:

你可以在SpringApplication的帮助下以编程方式关闭Boot应用程序。它有一个静态的exit()方法,需要两个参数:ApplicationContextExitCodeGenerator

@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

7.配置日志记录级别

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:

你可以轻松地调整Boot应用程序中的日志级别;从1.2.0版开始,你可以在主属性文件中配置日志级别。

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.

就像标准的Spring应用一样–你可以通过在classpath中添加自定义的XML或属性文件并在pom中定义库来激活不同的日志系统,如Logbacklog4jlog4j2等等。

8. Register a New Servlet

8.注册一个新的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:

如果你在嵌入式服务器的帮助下部署应用程序,你可以在Boot应用程序中注册新的Servlet,通过将它们作为Bean从常规配置中公开。

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

Alternatively, you can use a ServletRegistrationBean:

或者,你可以使用一个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

9.在启动程序中配置Jetty或Undertow

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:

Spring Boot的启动程序通常使用Tomcat作为默认的嵌入式服务器。如果需要改变这一点–你可以排除Tomcat的依赖关系,改用Jetty或Undertow。

Configuring Jetty

配置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

配置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

10.结论

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

在这篇快速文章中,我们回顾了一些比较有趣和有用的Spring Boot配置选项

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.

当然,在参考文档中还有很多很多的选项,可以根据你的需要配置和调整Boot应用程序,这些只是我发现的一些比较有用的选项。

The code used in this article can be found over on our Github repository.

本文使用的代码可以在我们的Github资源库中找到