美文网首页
Java代码瘦身工具:Lombok

Java代码瘦身工具:Lombok

作者: 5946a9de5796 | 来源:发表于2018-04-05 11:57 被阅读37次

    安装方法

    为项目导入maven依赖

    在pom中添加依赖:

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

    为IDEA安装Lombok插件

    在IDEA中想要使用Lombok还需要安装一个插件,打开Plugins,搜索并安装Lombok Plugin这个插件。


    image

    使用方法

    自动添加get、set方法

    在需要添加get和set方法的类中添加@Data注解,这个注解是包含了Getter、Setter和toString等注解,如果只需要其中之一的话也可以单独使用@Getter等注解。

    这样就完成了,只需简单地添加一个注解,便可以使代码变得无比清爽。
    看一下对比效果:

    使用前:
    已经去掉了很多换行,但还是给人一种非常臃肿的感觉。

    @Entity
    @DynamicUpdate
    public class ProductCategory {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer categoryId;
        private String categoryName;
        private Integer categoryType;
        private Date updateTime;
        private Date createTime;
    
        public Integer getCategoryId() {
            return categoryId;
        }
        public void setCategoryId(Integer categoryId) {
            this.categoryId = categoryId;
        }
        public String getCategoryName() {
            return categoryName;
        }
        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }
        public Integer getCategoryType() {
            return categoryType;
        }
        public void setCategoryType(Integer categoryType) {
            this.categoryType = categoryType;
        }
        public Date getUpdateTime() {
            return updateTime;
        }
        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }
        public Date getCreateTime() {
            return createTime;
        }
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
        @Override
        public String toString() {
            return "ProductCategory{" +
                    "categoryId=" + categoryId +
                    ", categoryName='" + categoryName + '\'' +
                    ", categoryType=" + categoryType +
                    '}';
        }
    }
    

    使用后:

    @Entity
    @DynamicUpdate
    @Data
    public class ProductCategory {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer categoryId;
    
        private String categoryName;
    
        private Integer categoryType;
    
        private Date updateTime;
    
        private Date createTime;
    
    }
    

    不仅代码变得简洁清爽,日后在修改变量类型时,也不再需要一个一个去修改方法的返回类型,提高了编码效率。

    相关文章

      网友评论

          本文标题:Java代码瘦身工具:Lombok

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