pom.xml配置

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.16.16</version>
</dependency>

Lombok主要注解

  • @Getter and @Setter / 自动为属性提供 Set和Get 方法
  • @ToString / 该注解的作用是为类自动生成toString()方法
  • @EqualsAndHashCode / 为对象字段自动生成hashCode和equals实现
  • @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor / 顾名思义,为类自动生成对应参数的constructor
  • @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog / 自动为类添加对应的log支持
  • @Data / 自动为所有字段添加@ToString, @EqualsAndHashCode, @Getter,为非final字段添加@Setter and @RequiredArgsConstructor,本质上相当于几个注解的综合效果
  • @NonNull / 自动帮助我们避免空指针。作用在方法参数上的注解,用于自动生成空值参数检查
  • @Cleanup / 自动帮我们调用close()方法。作用在局部变量上,在作用域结束时会自动调用close方法释放资源

下文就Lombok中用的最为频繁的@Data和@Log注解进行代码实战!

@Data注解使用

  • 其可以看成是多个Lombok注解的集成,因此使用很方便!

  • 先来创建一个POJO实体UserLombok,普通的写法如下:

public class UserLombok {
  private final String name;
  private int age;
  private double score;
  private String[] tags;
  
  public UserLombok(String name) {
    this.name = name;
  }
  
  public String getName() {
    return this.name;
  }
  
  void setAge(int age) {
    this.age = age;
  }
  
  public int getAge() {
    return this.age;
  }
  
  public void setScore(double score) {
    this.score = score;
  }
  
  public double getScore() {
    return this.score;
  }
  
  public String[] getTags() {
    return this.tags;
  }
  
  public void setTags(String[] tags) {
    this.tags = tags;
  }
  
  @Override public String toString() {
    return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + “)”;
  }
  
  protected boolean canEqual(Object other) {
    return other instanceof DataExample;
  }
  
  @Override public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof DataExample)) return false;
    DataExample other = (DataExample) o;
    if (!other.canEqual((Object)this)) return false;
    if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
    if (this.getAge() != other.getAge()) return false;
    if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
    if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
    return true;
  }
  
  @Override public int hashCode() {
    final int PRIME = 59;
    int result = 1;
    final long temp1 = Double.doubleToLongBits(this.getScore());
    result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
    result = (result*PRIME) + this.getAge();
    result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
    result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
    return result;
  }
}
  • Lombok加持后,写法可简化为:
@Data
public class UserLombok {
    private final String name;
    private int age;
    private double score;
    private String[] tags;
}
  • 由于Lombok为我们自动生成了toString方法,因此对象的打印结果如下:
UserLombok(name=hansonwang99, age=18, score=99.0, tags=[apple, juice])

@Log注解实战

  • 使用Log4j2来作为日志对象,其写法如下:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/testlogging")
public class LoggingTestController {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @GetMapping("/hello")
    public String hello() {
        for (int i = 0; i < 10_0000; i++) {
            logger.info("info execute index method");
            logger.warn("warn execute index method");
            logger.error("error execute index method");
        }
        return "My First SpringBoot Application";
    }
}
  • 若改用Lombok后,写法变得更加简洁,我们只需要引入对应的@Log注解即可完成log对象的生成:
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Log4j2
public class Test {
    @GetMapping("/testLog")
    public String hello() {
        for (int i = 0; i < 1000; i++) {
            log.info("info execute index method");
            log.warn("warn execute index method");
            log.error("error execute index method");
        }
        return "My First SpringBoot Application";
    }
}

转载于https://www.codesheep.cn/2018/04/09/SpringBoot%E4%BC%98%E9%9B%85%E7%BC%96%E7%A0%81%E4%B9%8B%EF%BC%9ALombok%E5%8A%A0%E6%8C%81/


hhhhh