虽说“基础不牢,地动山摇”,但是也不能一直都停留在基础的环节,毕竟在公司总要干活的,说到干活,框架用的不6,那肯定就只能996,所以我在总结基础的同时,也会偶尔分享一下框架的一些基础知识,如果在阅读的你是已经步入职场的大佬,那这篇文件你可以不用看了,这篇文章主要是为刚学习框架,或者想要学习框架的码友看的,这里啰嗦一句框架使用三部曲:引入依赖 、编写配置、使用,嘿嘿,废话不多说,肝就完了。 技术点: 1.springboot2.1.5 2.mybatis 3.mybatis generator 4.logback 5.hibernate validator
1. 创建项目,并引入依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--SpringBoot通用依赖模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--SpringBoot监控模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--Spring切面模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!--SpringBoot测试模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--MyBatis分页插件,会自动引入mybatis的框架--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.10</version> </dependency> <!--集成druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- MyBatis 生成器 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.6</version> </dependency> <!--Mysql数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> </dependencies>2. 编写配置 2.1 application.yml的配置:
server: port: 8888 spring: datasource: url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: xsy123 ##指定mybatis的mapper映射文件路径 mybatis: mapper-locations: - classpath:mapper/*.xml - classpath*:com/**/mapper/*.xml2.2 创建springboot的启动类
@SpringBootApplication public class MallMylearningApplication { public static void main(String[] args) { SpringApplication.run(MallMylearningApplication.class, args); } }2.3 此致springboot的配置已经足够启动一个项目,下面讲解generator Mapper代码自动生成及mybatis的配置。 2.3.1 添加配置: 在resource目录下创建generatorConfig.xml,并添加如下内容
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <properties resource="generator.properties"/> <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <property name="javaFileEncoding" value="UTF-8"/> <!-- 为模型生成序列化方法--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <!-- 为生成的Java模型创建一个toString方法 --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!--可以自定义生成model的代码注释--> <commentGenerator type="com.rzx.mall.mallmylearning.mbg.CommentGenerator"> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> <property name="addRemarkComments" value="true"/> </commentGenerator> <!--配置数据库连接--> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}"> <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题--> <property name="nullCatalogMeansCurrent" value="true" /> </jdbcConnection> <!--指定生成model的路径--> <javaModelGenerator targetPackage="com.rzx.mall.mallmylearning.mbg.model" targetProject="src\main\java"/> <!--指定生成mapper.xml的路径--> <sqlMapGenerator targetPackage="com.rzx.mall.mallmylearning.mbg.mapper" targetProject="src\main\resources"/> <!--指定生成mapper接口的的路径--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.rzx.mall.mallmylearning.mbg.mapper" targetProject="src\main\java"/> <!--生成全部表tableName设为%,一次生成多个表复制多个table配置--> <table tableName="pms_brand"> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> </context> </generatorConfiguration>2.3.2 在resource目录下创建generator.properties,并添加如下内容
##主要用于generator框架连接数据库,生成mapper代码用的,generatorConfig.xml中指定使用配置文件generator.properties ###数据库连接配置 jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai jdbc.userId=root jdbc.password=xsy1232.3.3 创建代码生成类
package com.rzx.mall.mallmylearning.mbg; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * 用于生产MBG的代码 * Created by macro on 2018/4/26. */ public class Generator { public static void main(String[] args) throws Exception { //MBG 执行过程中的警告信息 List<String> warnings = new ArrayList<String>(); //当生成的代码重复时,覆盖原代码 boolean overwrite = true; //读取我们的 MBG 配置文件 InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite); //创建 MBG MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); //执行生成代码 myBatisGenerator.generate(null); //输出警告信息 for (String warning : warnings) { System.out.println(warning); } } }CommentGenerator 自定义注释生成器,用于生产字段注释,前提是在创建数据库表时指定comment注释
package com.rzx.mall.mallmylearning.mbg; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.internal.DefaultCommentGenerator; import org.mybatis.generator.internal.util.StringUtility; import java.util.Properties; /** * 自定义注释生成器 * Created by macro on 2018/4/26. */ public class CommentGenerator extends DefaultCommentGenerator { private boolean addRemarkComments = false; /** * 设置用户配置的参数 */ @Override public void addConfigurationProperties(Properties properties) { super.addConfigurationProperties(properties); this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments")); } /** * 给字段添加注释 */ @Override public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { String remarks = introspectedColumn.getRemarks(); //根据参数和备注信息判断是否添加备注信息 if (addRemarkComments && StringUtility.stringHasValue(remarks)) { addFieldJavaDoc(field, remarks); } } /** * 给model的字段添加注释 */ private void addFieldJavaDoc(Field field, String remarks) { //文档注释开始 field.addJavaDocLine("/**"); //获取数据库字段的备注信息 String[] remarkLines = remarks.split(System.getProperty("line.separator")); for (String remarkLine : remarkLines) { field.addJavaDocLine(" * " + remarkLine); } addJavadocTag(field, false); field.addJavaDocLine(" */"); } }2.3.4 右键运行代码生成类,自动生成mapper代码,生成的代码如下: 2.3.5 mapper扫描,告诉框架使用动态代理在运行时生成mapper实现类
package com.rzx.mall.mallmylearning.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; @Configuration @MapperScan("com.rzx.mall.mallmylearning.mbg.mapper") public class MyBatisConfig { }到这里总结一下,我们前面都完成了哪些工作:1.springboot与mybatis的整合 2.generator框架的整合与使用,并自动创建完毕mapper层的代码,那么接下来我们剩余哪些工作呢?是不是service层和controller层代码我们没写?接下来就带来大家简单来完成这块代码的编写。
3. 框架使用 3.1 service层代码编写 接口:
package com.rzx.mall.mallmylearning.service; import com.rzx.mall.mallmylearning.mbg.model.PmsBrand; import java.util.List; /** * @author: xieshiyao@1218.com.cn * @Date: 2020/7/3 22:19 * @Description: 品牌相关接口 */ public interface PmsBrandService { /** * @author: xieshiyao@1218.com.cn * @Date: 2020/7/3 22:19 * @Description: 查询全部 */ List<PmsBrand> listAllBrand(); /** * @author: xieshiyao@1218.com.cn * @Date: 2020/7/3 22:20 * @Description: 添加品牌 */ int createBrand(PmsBrand pmsBrand); /** * @author: xieshiyao@1218.com.cn * @Date: 2020/7/3 22:20 * @Description: */ int updateBrand(Long id ,PmsBrand pmsBrand); int deleteBrand(Long id); List<PmsBrand> listBrand(int pageSize,int pageNo); PmsBrand getBrand(Long id); }实现:
package com.rzx.mall.mallmylearning.service.impl; import com.github.pagehelper.PageHelper; import com.rzx.mall.mallmylearning.mbg.mapper.PmsBrandMapper; import com.rzx.mall.mallmylearning.mbg.model.PmsBrand; import com.rzx.mall.mallmylearning.mbg.model.PmsBrandExample; import com.rzx.mall.mallmylearning.service.PmsBrandService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PmsBrandServiceImpl implements PmsBrandService { @Autowired private PmsBrandMapper pmsBrandMapper; @Override public List<PmsBrand> listAllBrand() { return pmsBrandMapper.selectByExample(new PmsBrandExample()); } @Override public int createBrand(PmsBrand pmsBrand) { return pmsBrandMapper.insertSelective(pmsBrand); } @Override public int updateBrand(Long id, PmsBrand pmsBrand) { pmsBrand.setId(id); return pmsBrandMapper.updateByPrimaryKeySelective(pmsBrand); } @Override public int deleteBrand(Long id) { return pmsBrandMapper.deleteByPrimaryKey(id); } @Override public List<PmsBrand> listBrand(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); return pmsBrandMapper.selectByExample(new PmsBrandExample()); } @Override public PmsBrand getBrand(Long id) { return pmsBrandMapper.selectByPrimaryKey(id); } }3.2 controller层代码编写
package com.rzx.mall.mallmylearning.controller; import com.rzx.mall.mallmylearning.common.api.CommonPage; import com.rzx.mall.mallmylearning.common.api.CommonResult; import com.rzx.mall.mallmylearning.mbg.model.PmsBrand; import com.rzx.mall.mallmylearning.service.PmsBrandService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @Controller @RequestMapping("/brand") public class PmsBrandController { @Autowired private PmsBrandService pmsBrandService; private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class); @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsBrand>> getBrandList() { return CommonResult.success(pmsBrandService.listAllBrand()); } @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) { CommonResult commonResult; int count = pmsBrandService.createBrand(pmsBrand); if (count == 1) { commonResult = CommonResult.success(pmsBrand); LOGGER.debug("createBrand success:{}", pmsBrand); } else { commonResult = CommonResult.failed("操作失败"); LOGGER.debug("createBrand failed:{}", pmsBrand); } return commonResult; } @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody @Valid PmsBrand pmsBrand, BindingResult bindingResult) { CommonResult commonResult; //@Valid PmsBrand 校验结果会绑定到BindingResult对象中 if (bindingResult.hasErrors()) { commonResult = CommonResult.failed(bindingResult.getFieldError().getDefaultMessage()); return commonResult; } int count = pmsBrandService.updateBrand(id, pmsBrand); if (count == 1) { commonResult = CommonResult.success(pmsBrand); LOGGER.debug("updateBrand success:{}", pmsBrand); } else { commonResult = CommonResult.failed("操作失败"); LOGGER.debug("updateBrand failed:{}", pmsBrand); } return commonResult; } @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET) @ResponseBody public CommonResult deleteBrand(@PathVariable(value = "id", required = true) Long id) { CommonResult commonResult; int count = pmsBrandService.deleteBrand(id); if (count == 1) { commonResult = CommonResult.success(null); LOGGER.debug("deleteBrand success :id={}", id); } else { commonResult = CommonResult.failed("操作失败"); LOGGER.debug("deleteBrand failed :id={}",id); } return commonResult; } @RequestMapping(value = "/list",method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){ List<PmsBrand> pmsBrands = pmsBrandService.listBrand(pageSize, pageNum); return CommonResult.success(CommonPage.restPage(pmsBrands)); } @RequestMapping(value = "/get/{id}",method = RequestMethod.GET) public CommonResult getBrand(@PathVariable(value = "id",required = true) Long id){ return CommonResult.success(pmsBrandService.getBrand(id)); } }附录: 通用响应CommonResult类:
package com.rzx.mall.mallmylearning.common.api; /** * 通用返回对象 * Created by macro on 2019/4/19. */ public class CommonResult<T> { private long code; private String message; private T data; protected CommonResult() { } protected CommonResult(long code, String message, T data) { this.code = code; this.message = message; this.data = data; } /** * 成功返回结果 * * @param data 获取的数据 */ public static <T> CommonResult<T> success(T data) { return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data); } /** * 成功返回结果 * * @param data 获取的数据 * @param message 提示信息 */ public static <T> CommonResult<T> success(T data, String message) { return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data); } /** * 失败返回结果 * @param errorCode 错误码 */ public static <T> CommonResult<T> failed(IErrorCode errorCode) { return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null); } /** * 失败返回结果 * @param message 提示信息 */ public static <T> CommonResult<T> failed(String message) { return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null); } /** * 失败返回结果 */ public static <T> CommonResult<T> failed() { return failed(ResultCode.FAILED); } /** * 参数验证失败返回结果 */ public static <T> CommonResult<T> validateFailed() { return failed(ResultCode.VALIDATE_FAILED); } /** * 参数验证失败返回结果 * @param message 提示信息 */ public static <T> CommonResult<T> validateFailed(String message) { return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null); } /** * 未登录返回结果 */ public static <T> CommonResult<T> unauthorized(T data) { return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data); } /** * 未授权返回结果 */ public static <T> CommonResult<T> forbidden(T data) { return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data); } public long getCode() { return code; } public void setCode(long code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } }通用分页响应类CommonPage:
package com.rzx.mall.mallmylearning.common.api; import com.github.pagehelper.PageInfo; import java.util.List; /** * 分页数据封装类 * Created by macro on 2019/4/19. */ public class CommonPage<T> { private Integer pageNum; private Integer pageSize; private Integer totalPage; private Long total; private List<T> list; /** * 将PageHelper分页后的list转为分页信息 */ public static <T> CommonPage<T> restPage(List<T> list) { CommonPage<T> result = new CommonPage<T>(); PageInfo<T> pageInfo = new PageInfo<T>(list); result.setTotalPage(pageInfo.getPages()); result.setPageNum(pageInfo.getPageNum()); result.setPageSize(pageInfo.getPageSize()); result.setTotal(pageInfo.getTotal()); result.setList(pageInfo.getList()); return result; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getTotalPage() { return totalPage; } public void setTotalPage(Integer totalPage) { this.totalPage = totalPage; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } }返回错误码封装:
package com.rzx.mall.mallmylearning.common.api; /** * 封装API的错误码 * Created by macro on 2019/4/19. */ public interface IErrorCode { long getCode(); String getMessage(); } package com.rzx.mall.mallmylearning.common.api; /** * 枚举了一些常用API操作码 * Created by macro on 2019/4/19. */ public enum ResultCode implements IErrorCode { SUCCESS(200, "操作成功"), FAILED(500, "操作失败"), VALIDATE_FAILED(404, "参数检验失败"), UNAUTHORIZED(401, "暂未登录或token已经过期"), FORBIDDEN(403, "没有相关权限"); private long code; private String message; private ResultCode(long code, String message) { this.code = code; this.message = message; } public long getCode() { return code; } public String getMessage() { return message; } }到这里,一个基本的可用于生产的springBoot+Mybatis集成环境已经搭建完毕,接下来就是进行测试
三、测试 四、项目使用到的技巧总结 4.1 如何在代码中进行优雅的参数校验之hibernate.validator BindingResult与@Valid注解结合实现controller参数校验,步骤 1.在实体类需要校验的字段中添加注解
/** * 14 * Bean Validation 中内置的 constraint * 15 * @Null 被注释的元素必须为 null * 16 * @NotNull 被注释的元素必须不为 null * 17 * @AssertTrue 被注释的元素必须为 true * 18 * @AssertFalse 被注释的元素必须为 false * 19 * @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 * 20 * @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 * 21 * @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 * 22 * @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 * 23 * @Size(max=, min=) 被注释的元素的大小必须在指定的范围内 * 24 * @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内 * 25 * @Past 被注释的元素必须是一个过去的日期 * 26 * @Future 被注释的元素必须是一个将来的日期 * 27 * @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式 * 28 * Hibernate Validator 附加的 constraint * 29 * @NotBlank(message =) 验证字符串非null,且长度必须大于0 * 30 * @Email 被注释的元素必须是电子邮箱地址 * 31 * @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内 * 32 * @NotEmpty 被注释的字符串的必须非空 * 33 * @Range(min=,max=,message=) 被注释的元素必须在合适的范围内 * 34 */ public class PmsBrand implements Serializable { private Long id; @NotEmpty(message = "名称不能为空") private String name; /** * 首字母 * * @mbg.generated */ private String firstLetter; private Integer sort; /** * 是否为品牌制造商:0->不是;1->是 * * @mbg.generated */ private Integer factoryStatus; @Max(value = 30, message = "参数值不能大于30") private Integer showStatus; ......省略get/set **2.在参数(不一定是控制器)中添加@valid注解和BindingResult,如果有多个实体需要校验,保证 @valid和BindingResult成对先后顺序出现即可** @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody //@Valid PmsBrand pmsBrand, BindingResult bindingResult 配合使用 public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody @Valid PmsBrand pmsBrand, BindingResult bindingResult) { CommonResult commonResult; //@Valid PmsBrand 校验结果会绑定到BindingResult对象中 if (bindingResult.hasErrors()) { commonResult = CommonResult.failed(bindingResult.getFieldError().getDefaultMessage()); return commonResult; } .....省略其它代码好了到这里,hibernate.validator的校验我也已经通过一个使用场景演示完毕,如果你代码中还是使用if/else验证代码,那请纠正过来,那种代码一点都不优雅,要让你的代码如诗一样优雅哈哈,这是一种编程素养。
4.2 引入日志配置,控制日志输出 日志在开发中的重要性,我这里就不说了,合理的记录日志,是排查线上问题的关键,这里我主要讲解单机日志的配置及输出,虽然我们现在线上的环境已经是将日志推送到ELK中了,不过原理都类似一个是将日志保存到本地,一个是将日志传输到远程,并提供可视化界面查看日志(建议新的项目都使用这种方式,或者老的项目也尽量使用ELK这种方式,我们可以对日志进行分析且不用到服务器上download就能够通过可视化工具查看日志,非常方便)。 前面在配置环境的时候,没有提到日志的输出,springboot依赖在引入的同时就已经将日志框架logback一起引入到了工程中了,所以依赖我们不需要单独引入 在resource目录下创建logback.xml,并添加如下内容
<?xml version="1.0" encoding="UTF-8" ?> <configuration scan="true" scanPeriod="3 seconds"> <!--设置日志输出为控制台,一个appender代表一个输入方式的配置--> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <!--日志输出的格式--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%logger{32}] %msg%n</pattern> </encoder> </appender> <!--设置日志输出为文件--> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!--指定文件名称--> <File>logFile.log</File> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--隔天自动切割并压缩日志文件存放--> <FileNamePattern>logFile.%d{yyyy-MM-dd_HH-mm}.log.zip</FileNamePattern> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <!--日志输出的格式--> <Pattern>%d{HH:mm:ss,SSS} [%thread] %-5level %logger{32} - %msg%n</Pattern> </layout> </appender> <!--root指定启用哪几个appender配置,通过ref与name对应--> <root> <!--指定日志输出级别,开发环境可以使用DEBUG但是到了线上,应该替换为INFO--> <level value="DEBUG"/> <appender-ref ref="STDOUT"/> <appender-ref ref="FILE"/> </root> </configuration>代码中使用:
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class); //{}表示字符串站位符号,pmsBrand实体需要提供toString方法,最终的结果就是调用参数2的toString方法获取字符串,然后替换{}占位符 LOGGER.debug("updateBrand success:{}", pmsBrand);下集预告,下一篇文章我主要对Swagger的内容进行讲解