Lombok

作者: 芒鞋儿 | 来源:发表于2023-02-19 13:12 被阅读0次

    Lombok 主要用来节省一些写pojo class的effort, 是一个annotation based library.用以下的一些annotation 可以省去写一些代码。

    Lombok annotations:
    @Getter
    @Setter
    @NoArgsConstructor
    @RequiredArgsConstructor
    @AllArgsConstructor
    @ToString
    @EqualsAndHashCode
    @Data

    @Data is the combination of:
    @Getter
    @Setter
    @RequiredArgsConstructor
    @ToString
    @EqualsAndHashCode
    before:

    
    public class Holiday {
        private String day;
        private String reason;
        private Type type;
    
        public Holiday(String day, String reason, Type type) {
            this.day = day;
            this.reason = reason;
            this.type = type;
        }
    
        public enum Type {
            FESTIVAL, FEDERAL
        }
    
        public Type getType() {
            return type;
        }
    
        public String getDay() {
            return day;
        }
    
        public String getReason() {
            return reason;
        }
    }
    

    after:

    import lombok.Data;
    
    @Data
    public class Holiday {
        private String day;
        private String reason;
        private Type type;
    
        public enum Type {
            FESTIVAL, FEDERAL
        }
    
    }
    

    Lombok 的另一个feature是Slf4j, 可以用 @Slf4j 省略掉写Logger 类的功夫。
    before:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Service;
    
    
    @Service
    public class ContactService {
        private static Logger log = LoggerFactory.getLogger(ContactService.class);
    
        public boolean saveMessageDetail(Contact contact){
            boolean isSaved = true;
            log.info(contact.toString());
            return isSaved;
        }
    }
    

    after

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    
    @Slf4j
    @Service
    public class ContactService {
        public boolean saveMessageDetail(Contact contact){
            boolean isSaved = true;
            log.info(contact.toString());
            return isSaved;
        }
    }
    

    official site:
    https://projectlombok.org/

    refer:
    https://auth0.com/blog/a-complete-guide-to-lombok/
    https://www.baeldung.com/intro-to-project-lombok

    相关文章

      网友评论

          本文标题:Lombok

          本文链接:https://www.haomeiwen.com/subject/xcmikdtx.html