大家在编写springboot项目的过程中可能会接触到lombok这个插件,这个插件可以在编译时帮我生成很多代码。

1、@Data生成Getter和Setter代码,用于类名注释

2、@Getter 生成字段对应的getXXX方法

3、@Setter生成字段对应的setXXX(xxx yyy)方法

4、@Builder构造器设计模式生成个字段的设置属性方法,该字段一般用于一些类参数可以选,可单选,可多选的环境中

5、@Slf4j使用Slf4j中门面模式,适配底层日志框架,slf4j和底层日志框架协调记录日志

6、@NoArgsConstructor生成类的默认构造函数

7、@AllArgsConstructor生成类所有字段的构造函数,常常和@Builder同时出现

8、@ToString,笔者不常用这个

9、var 兼容ECMA规范,可以编译时自动推断数类型的注解

代码如下

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import lombok.var; @Data
@Getter
@Setter
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class LombokClass {
@Setter
private Integer id; @Setter
@Getter
private String name; public void test()
{
var t ="s";
} }

生成代码:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class LombokClass
{
private static final Logger log;
private Integer id;
private String name; public void test() {
final String t = "s";
} public static LombokClassBuilder builder() {
return new LombokClassBuilder();
} @Override
public boolean equals(final Object o) {
if (o == this) {
return true;
}
if (!(o instanceof LombokClass)) {
return false;
}
final LombokClass other = (LombokClass)o;
if (!other.canEqual(this)) {
return false;
}
final Object this$id = this.getId();
final Object other$id = other.getId();
Label_0065: {
if (this$id == null) {
if (other$id == null) {
break Label_0065;
}
}
else if (this$id.equals(other$id)) {
break Label_0065;
}
return false;
}
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null) {
if (other$name == null) {
return true;
}
}
else if (this$name.equals(other$name)) {
return true;
}
return false;
} protected boolean canEqual(final Object other) {
return other instanceof LombokClass;
} @Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = this.getId();
result = result * 59 + (($id == null) ? 43 : $id.hashCode());
final Object $name = this.getName();
result = result * 59 + (($name == null) ? 43 : $name.hashCode());
return result;
} public Integer getId() {
return this.id;
} public LombokClass() {
} public LombokClass(final Integer id, final String name) {
this.id = id;
this.name = name;
} @Override
public String toString() {
return "LombokClass(id=" + this.getId() + ", name=" + this.getName() + ")";
} public void setId(final Integer id) {
this.id = id;
} public void setName(final String name) {
this.name = name;
} public String getName() {
return this.name;
} static {
log = LoggerFactory.getLogger((Class)LombokClass.class);
} public static class LombokClassBuilder
{
private Integer id;
private String name; LombokClassBuilder() {
} public LombokClassBuilder id(final Integer id) {
this.id = id;
return this;
} public LombokClassBuilder name(final String name) {
this.name = name;
return this;
} public LombokClass build() {
return new LombokClass(this.id, this.name);
} @Override
public String toString() {
return "LombokClass.LombokClassBuilder(id=" + this.id + ", name=" + this.name + ")";
}
}
}

本文要讲解的重点是@Slf4j相关的使用,使用该注解默认生成代码如下

import org.slf4j.Logger;

private static final Logger log = org.slf4j.LoggerFactory.getLogger(当前类名.class);

log有以下几个方法info,trace,debug,error,warn及对应的重载方法。

追踪了一下代码,内部会使用StringBuilder这个线程安全类处理,StringBuilder比String速度比较快,他不会创建多个String对象。

以上几个方法常用格式化代码如下(使用{}作为占位符):

来自:https://examples.javacodegeeks.com/enterprise-java/slf4j/slf4j-format-string-example/

package com.javacodegeeks.slf4.formatting;

import java.lang.invoke.MethodHandles;
import java.text.MessageFormat;
import java.util.Calendar; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Substituting Parameters!
*
*/
public class Slf4jSusbstitutionExample
{
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public static void main( String[] args )
{
String user = "john";
String application = "gateway"; // Crafting a message without substitution.
// Not a good idea as the String concatenation and evaluation will happen irrespective of whether
// logging level is permissible or not to be logged.
LOGGER.info("Bad experience for user " + user + " at time " + Calendar.getInstance().getTime()); // Substitution with one formatting anchor and one argument
LOGGER.info("Bad experience for user {}", user); // If you happen to forget to provide a substituting object
LOGGER.info("Bad experience for user {}"); // Substitution with two formatting anchors and two arguments
LOGGER.info("Bad experience for user {} at time {}", user, Calendar.getInstance().getTime()); // Substitution with three formatting anchors and three arguments
LOGGER.info("Bad experience for user {} at time {} while accessing {}", user, Calendar.getInstance().getTime(), application); // Escaping formatting anchor
LOGGER.info("ERROR CODE \\{}; Bad experience for user {} at time {}", user, Calendar.getInstance().getTime()); // Formatting anchor with data inside; no problem
LOGGER.info("ERROR CODE {22}; Bad experience for user {} at time {}", user, Calendar.getInstance().getTime()); // Crafting a message with Java's own MessageFormatter.
// Not a good idea as per SLF4J's documentation.
// 1. SLF4J's implementation is 10 times faster than that of MessageFormat.
// 2. Moreover to make sure that the evaluation happens only if that particular logging
// level is allowed, you need to do a check.
if(LOGGER.isInfoEnabled()) {
String message = MessageFormat.format("Bad experience for user {0} at time {1} while accessing {2}", user, Calendar.getInstance().getTime(), application);
LOGGER.info(message);
}
}
}

输出结果:

2017-04-20 20:25:42 INFO  Slf4jSusbstitutionExample - Bad experience for user john at time Thu Apr 20 20:25:42 IST 2017
2017-04-20 20:25:42 INFO Slf4jSusbstitutionExample - Bad experience for user john
2017-04-20 20:25:42 INFO Slf4jSusbstitutionExample - Bad experience for user {}
2017-04-20 20:25:42 INFO Slf4jSusbstitutionExample - Bad experience for user john at time Thu Apr 20 20:25:42 IST 2017
2017-04-20 20:25:42 INFO Slf4jSusbstitutionExample - Bad experience for user john at time Thu Apr 20 20:25:42 IST 2017 while accessing gateway
2017-04-20 20:25:42 INFO Slf4jSusbstitutionExample - ERROR CODE {}; Bad experience for user john at time Thu Apr 20 20:25:42 IST 2017
2017-04-20 20:25:42 INFO Slf4jSusbstitutionExample - ERROR CODE {22}; Bad experience for user john at time Thu Apr 20 20:25:42 IST 2017
2017-04-20 20:25:42 INFO Slf4jSusbstitutionExample - Bad experience for user john at time 4/20/17 8:25 PM while accessing gateway

本博客lombok其他文章:

idea中Lombok的Buider构造器模式,getter/setter正确使用方法

lombok编译时注解@Slf4j的使用及相关依赖包

Lombok子类与父类的@Builder注解冲突

lombok插件/slf4j中字符串格式化的更多相关文章

  1. python中字符串格式化%与.format

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...

  2. python中字符串格式化的意义(化妆)

    格式 描述%% 百分号标记 #就是输出一个%%c 字符及其ASCII码%s 字符串%d 有符号整数(十进制)%u 无符号整数(十进制)%o 无符号整数(八进制)%x 无符号整数(十六进制)%X 无符号 ...

  3. lombok插件@Slf4j注解不生效问题解决办法

    最近在尝试使用日志工具Sfl4j,当时使用log时报错,找了好久才解决这个问题. 1.首先需要下载Lombok插件 File->settings->Plugins 搜索Lombok,点击安 ...

  4. python中字符串格式化的两种方法

    知识点汇总;1-字符串格式化输出方法一: % 1-print('名字是 %s,年龄是%s' % (name ,age)) 2- %s ---字符串-----相当于执行了str() 3- (name , ...

  5. python中字符串格式化的四种方法

    name = "huangemiling" age= 10 address = 'nanjing' print("My name is %s,age is %d,I co ...

  6. python中字符串格式化

    username='小黑'age=18high=1.88s2='欢迎%s,年龄是%d,身高是%.2f'%(username,age,high)#%s是通用的,%d就必须传整数,%f就必须是小数,想保留 ...

  7. [翻译]python3中新的字符串格式化方法-----f-string

    从python3.6开始,引入了新的字符串格式化方式,f-字符串. 这使得格式化字符串变得可读性更高,更简洁,更不容易出现错误而且速度也更快. 在本文后面,会详细介绍f-字符串的用法. 在此之前,让我 ...

  8. Python_Day_5装饰器、字符串格式化、序列化、内置模块、生成器、迭代器之篇

    一.装饰器 为什么要用装饰器??? 在实际的开发环境中应遵循开发封闭原则,虽然在这个原则是用的面向对象开发,但也适用于函数式编程,简单地说,它规定已经实现的功能代码不是允许修改的,但是可以被扩展: 封 ...

  9. Python:字符串格式化

    Python中提供了多种格式化字符串的方式,遇到一个项目,在一个文件中,就用了至少两种方式.特别是在使用Log时,更让人迷惑. 因此特地花时间来了解一下Python中字符串格式化的几种方式: # -* ...

随机推荐

  1. drf框架 - 过滤组件 | 分页组件 | 过滤器插件

    drf框架 接口过滤条件 群查接口各种筛选组件数据准备 models.py class Car(models.Model): name = models.CharField(max_length=16 ...

  2. Dubbo源码分析(3):ExtensionFactory

    通过ExtensionFactory的getExtension方法获取目标对象.ExtensionFactory实现有两个,一个基于SPI的,一个Spring的ApplicationContext的. ...

  3. YAML_10 把监听端口是8080的Apache服务全部停止

    ansible]# vim ad.yml --- - hosts: cache   remote_user: root   tasks:     - shell: netstat -atunlp  | ...

  4. Luogu P1903 BZOJ 2120 数颜色 带修改的莫队

    https://www.luogu.org/problemnew/show/P1903 之前切过这道题,复习莫队再切一遍,不过我之前写的是主席树和树状数组,也不知道我当时怎么想的…… 这个题卡常我没写 ...

  5. pcl-qt使用QVTKWidget 与PCLVisualizer 显示雷达点云

    #ifndef PCLVIEWER_H #define PCLVIEWER_H #include "defines.h" #include <iostream> #in ...

  6. 24、Checkpoint原理剖析

    一.原理 1.Checkpoint是什么 Checkpoint,是Spark提供的一个比较高级的功能. 有的时候,比如说,我们的Spark应用程序,特别的复杂,然后呢,从初始的RDD开始,到最后整个应 ...

  7. 如何解决金蝶IKernel.exe报错 Windows Installer 错误 重新安装、无法卸载

    如何解决金蝶IKernel.exe报错 Windows Installer 错误 金蝶这个小婊子,就是这么贱. 卸载了高版本的,再安装低版本就不能安装上,死活都不能安装. 请手动启动一下Install ...

  8. css笔记 - flex弹性盒布局

    flex: display:-webkit-box | -moz-box;盒布局 -webkit-box-flex | -moz-box-flex;弹性盒布局 -webkit-box-ordinal- ...

  9. 实验五 遇到的问题:openssl: error while loading shared libraries: libssl.so.1.1

    遇到的问题 命令行:linux@ubuntu64-vm:~/exp/exp5$ openssl enc -aes-128-cbc -in test_aes.txt -out out.txt -pass ...

  10. Emmet语法规则

    HTML速写之Emmet语法规则 Emmet-写HTML/CSS快到飞起 在前端开发的过程中,最费时间的工作就是写 HTML.CSS 代码.一堆的标签.属性.括号等,头疼.这里推荐一个Emmet语法规 ...