在这篇短文中,我们将介绍 Spring Boot Web应用程序配置 的一些有趣方面。 我们将介绍一些Web应用程序最常用的配置。
Spring Boot带有智能构建功能,可以轻松创建Web或独立应用程序。Spring Boot可以为我们做很多事情,甚至不需要我们为Web应用程序编写一行代码。本文中,我们只介绍其中几个配置。
web应用最常见的一个配置是HTTP端口号,我们可以用下列几种方式轻松地为我们的web应用配置HTTP端口号:
对于properties文件:
server.port=9001
对于YAML文件:
server: port: 8083
我们也可以在Spring Boot中编程设置HTTP端口:
@Component
public class CustomConfigurationimplements EmbeddedServletContainerCustomizer{
/**
* Customize the specified {@link ConfigurableEmbeddedServletContainer}.
*
* @param container the container to customize
*/
@Override
public void customize(ConfigurableEmbeddedServletContainer container){
container.setPort(9001);
}
}
Spring Boot Web应用程序的默认上下文路径是“/”,Spring Boot提供了通过配置或以编程方式设置上下文路径的选项。
对于properties文件:
server.contextPath=/javadevjournal
对于YAML文件:
server: contextPath:/javadevjournal
我们在Spring Boot中也可以通过编程来设置Context路径:
@Component
public class CustomConfigurationimplements EmbeddedServletContainerCustomizer{
/**
* Customize the specified {@link ConfigurableEmbeddedServletContainer}.
*
* @param container the container to customize
*/
@Override
public void customize(ConfigurableEmbeddedServletContainer container){
container.setPort(9001);
container.setContextPath("/javadevjournal");
}
}
如果你正在用Spring Boot应用程序,那么你应该熟悉 While Label Error Page 。 如果我们没有指定自己的自定义bean,Spring Boot会自动注册BasciErrorController bean。 我们可以通过扩展ErrorController来定制这个bean。
@Controller
public class CustomErrorControllerimplements ErrorController{
private static final String PATH = "/error";
@RequestMapping(value = PATH)
public String error(){
return "errorHandling";
}
/**
* Returns the path of the error page.
*
* @return the error path
*/
@Override
public String getErrorPath(){
return PATH;
}
}
Spring Boot提供了一种基于错误代码使用我们自己的自定义错误页面的方法。 我们需要在/error目录下添加基于错误代码的页面,并且Spring Boot将根据错误代码使用正确的页面。
我们可以使用静态HTML,也可以使用模板来构建我们的自定义错误页面。 文件的名称应该是确切的状态码或系列通配符。
我们可以使用类似的结构来组织我们的模板。
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 5xx.html
+- <other public assets>
Spring Boot对日志记录没有必要的依赖(通用日志API除外)。 Spring Boot内部使用LoggingSystem,试图根据类路径的内容配置日志。
我们可以在 application.properties 文件里用 logging.level 这个前缀来设置日志级别从而可以微调Spring Boot应用的日志输出。
logging.level.org.springframework.web=DEBUG logging.level.org.hibernate=ERROR
我们可以在Spring Boot应用程序中使用不同的日志框架(Logback,Log4j2)。