SpringBoot学习四:日志框架、SpringBoot自动化配置

时间:2022-07-26
本文章向大家介绍SpringBoot学习四:日志框架、SpringBoot自动化配置,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

SpringBoot的日志模块选择 SpringBoot底层选择的日志抽象层是@Slf4j,日志的实现是Logback。 日志的使用

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");
  }
}

如果在使用了Lombok的话,可以使用@Slf4j注解进行使用日志框架。提供一个 属性名为log 的 log4j 日志对像。

@Slf4j
public class HelloWorld {
  public static void main(String[] args) {
    log.info("Hello World");
    log.error("hello world");
  }
}

在SpringBoot中使用@Slf4j+logback组合,如果整合其他模块的话,如MyBatis、Hibernate,其底层可能使用了不同版本的@Slf4j,在启动时,可能会版本冲突导致无法启动。 Spring解决方案: 1、将系统中其他日志框架先排除出去 2、用中间包来替换原有的日志框架 3、导入slf4j其他的实现 SpringBoot能自动适配所有的日志,而且底层使用slf4j+logback的方式记录日志,引入其他框架的时候,只需要把这个框架依赖的日志框架排除掉即可。

SpringBoot自动化配置

SpringBoot官网介绍: Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

1.Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans. 2.Support for serving static resources, including support for WebJars (see below). 3.Automatic registration of Converter, GenericConverter, Formatter beans. 4.Support for HttpMessageConverters (see below). 5.Automatic registration of MessageCodesResolver (see below). 6.Static index.html support. 7.Custom Favicon support (see below). 8.Automatic use of a ConfigurableWebBindingInitializer bean (see below)

1.自动配置视图解析器,根据方法的返回值得到视图对象,视图对象决定如何渲染

2.支持静态资源文件夹路径,webjars 把静态文件放在这些路径下面,就会被加载到

“classpath:/META-INF/resources/”, “classpath:/resources/”, “classpath:/static/”, “classpath:/public/”;优先级顺序为:META-INF/resources > resources > static > public

3.自动注册Converter,GenericConverter和Formatter bean

  • Converter:转化,页面提交数据时,做类型转换,如用户年龄18,可以把18转换成Integer类型
  • Formatter:格式化,前端传入2020-8-9/2020.8.9/2020/8/9,等日期格式时,将数据格式化成Date类型
  • GenericConverter:支持在多个不同的原类型和目标类型之间进行转换 参考地址

4.支持HttpMessageConverters:SpringMVC用来转换Http请求和响应的;获取所有的HttpMessageConverter。

HttpMessageConverter :负责 json 数据进行交互。前端提交Json格式的数据被解析成 Java 对象作为 API入参,API 返回结果将 Java 对象解析成 json 格式数据返回给前端。

5.自动注册MessageCodesResolver:定义错误代码生成规则

Spring MVC有一个实现策略,用于从绑定的errors产生用来渲染错误信息的错误码:MessageCodesResolver。Spring Boot会自动为你创建该实现,只要设置spring.mvc.message-codes-resolver.format属性为PREFIX_ERROR_CODE或POSTFIX_ERROR_CODE

参考地址

6.静态 index.html 页面支持 7.自定义Favicon支持 8.自动使用ConfigurableWebBindingInitializer ConfigurableWebBindingInitializer的主要作用就是 :初始化WebDataBinder,将请求的参数转化为对应的JavaBean,并且会结合类型、格式转换等API一起使用。