V2EX 首页   注册   登录
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  程序员

SpringBoot 优雅编码之: Lombok 加持

  •  
  •   hansonwang99 · 几秒前 · 2 次点击

    小米游戏本


    概述

    Lombok 通过提供简单的语法注解形式来帮助简化消除一些必须有但显得很臃肿的 java 代码。典型的是对于 POJO 对象的简化(如自动帮我们生成 Setter 和 Getter 等),有了 Lombok 的加持,开发人员可以免去很多重复且臃肿的操作,极大地提高 java 代码的信噪比,因此我们必须尝试并应用起来!


    IntelliJ IDEA 上配置

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

    • 首先进入 Plugins 界面:

    进入 Plugins 界面

    • 然后搜索并安装 Lombok 插件:

    安装 Lombok 插件

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

    Enable Annotation Processors

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


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

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

    选择 lombok 的 zip 包来安装

    • 重启 idea 即可

    重启 IDEA 生效

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

    <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,和 @RequiredArgsConstructor,本质上相当于几个注解的综合效果
    • @NonNull / 自动帮助我们避免空指针。作用在方法参数上的注解,用于自动生成空值参数检查
    • @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 的注解会自动补全,如下图所示:

    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 自动生成的代码:

    自动生成的代码

    • 结果打印

    由于 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 的文章:


    CodeSheep

    目前尚无回复
    DigitalOcean
    关于   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   鸣谢   ·   904 人在线   最高记录 3541   ·  
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.0 · 17ms · UTC 23:20 · PVG 07:20 · LAX 16:20 · JFK 19:20
    ♥ Do have faith in what you're doing.
    沪ICP备16043287号-1