怎么在SpringBoot中实现Lombok加持

发布时间:2021-06-09 17:08:03 作者:Leah
来源:亿速云 阅读:104

这篇文章将为大家详细讲解有关怎么在SpringBoot中实现Lombok加持,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

IntelliJ IDEA上配置

方法一:直接在IDEA界面中配置

首先进入Plugins界面:

怎么在SpringBoot中实现Lombok加持

然后搜索并安装Lombok插件:

怎么在SpringBoot中实现Lombok加持

最后不要忘了开启Annotation Processors的Enable选项:

怎么在SpringBoot中实现Lombok加持

上述安装完成以后需要重启IDEA生效!

方法二:手动下载Lombok插件安装

有时由于网络原因,上面方法一这种方式安装失败,因此只能手动下载安装

下载lombok插件:

https://github.com/mplushnikov/lombok-intellij-plugin/releases

Plugins -> Install plugin from disk... 选择下载的zip包安装

怎么在SpringBoot中实现Lombok加持

重启idea即可

怎么在SpringBoot中实现Lombok加持

IDE中设置完成以后需要在pom.xml中添加如下所示的lombok依赖才能使用

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

Lombok主要注解

  1. @Getter and @Setter / 自动为属性提供 Set和Get 方法

  2. @ToString / 该注解的作用是为类自动生成toString()方法

  3. @EqualsAndHashCode / 为对象字段自动生成hashCode和equals实现

  4. @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor / 顾名思义,为类自动生成对应参数的constructor

  5. @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog / 自动为类添加对应的log支持

  6. @Data / 自动为所有字段添加@ToString, @EqualsAndHashCode, @Getter,为非final字段添加@Setter,和@RequiredArgsConstructor,本质上相当于几个注解的综合效果

  7. @NonNull / 自动帮助我们避免空指针。作用在方法参数上的注解,用于自动生成空值参数检查

  8. @Cleanup / 自动帮我们调用close()方法。作用在局部变量上,在作用域结束时会自动调用close方法释放资源

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

@Data注解使用

官网关于@Data注解的解释如下:

All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor!

不难理解,其可以看成是多个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;
}

在IDEA中使用时,Lombok的注解会自动补全,如下图所示:

怎么在SpringBoot中实现Lombok加持

我们来写POJO的测试代码

public static void main( String[] args ) {
    UserLombok userLombok = new UserLombok("hansonwang99”);
    userLombok.setAge(18);
    String[] array = new String[]{"apple","juice”};
    userLombok.setTags( array );
    userLombok.setScore( 99.0 );
    System.out.println(userLombok);
  }

由下图我们可以看到IDEA依然可以自动为我们补全由Lombok自动生成的代码:

怎么在SpringBoot中实现Lombok加持

结果打印

由于Lombok为我们自动生成了toString方法,因此对象的打印结果如下:

UserLombok(name=hansonwang99, age=18, score=99.0, tags=[apple, juice])

@Log注解实战

在我的文章 Spring Boot日志框架实践 一文中,我们使用Log4j2来作为日志对象,其写法如下:

@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对象的生成:

@RestController
@RequestMapping("/testloggingwithlombok”)
@Log4j2
public class LoggingTestControllerLombok {

  @GetMapping("/hello”)
  public String hello() {
    for(int i=0;i<10_0000;i++){
      log.info("info execute index method”);
      log.warn("warn execute index method”);
      log.error("error execute index method”);

    }

    return "My First SpringBoot Application”;
  }
}

关于怎么在SpringBoot中实现Lombok加持就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. springboot项目中使用lombok插件
  2. springboot--lombok注意事项

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot lombok

上一篇:python 中有哪些正则表达式语法

下一篇:怎么将springboot打包部署到linux服务器

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》