「Java笔记」 用 Lombok 解决代码 Getter/Setter等 又长又臭的问题

「Java笔记」 用 Lombok 解决代码 Getter/Setter等 又长又臭的问题

资源介绍参数
资源类别: Java
如遇问题: 联系客服/留言反馈
释放双眼,带上耳机,听听看~!

java-learning-notes

Java的一大特点,就是啰嗦。尤其是每个类中都要写Getter和Setter,真的是又长又丑。所以今天这里推荐一个神器:Lombok

那该怎么消除这些冗余的代码?简单几步操作。

首先看下原始代码:

@Entity
@DynamicUpdate//动态更新
public class ProductCategory {
    /**
     * 类目id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer categoryId;

    /**
     * 类目名字
     */
    private String categoryName;

    /**
     * 类目编号
     */
    private Integer categoryType;

    private  Date createTime;

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    private Date updateTime;

    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;
    }

    @Override
    public String toString() {
        return "ProductCategory{" +
                "categoryId=" + categoryId +
                ", categoryName='" + categoryName + ''' +
                ", categoryType=" + categoryType +
                '}';
    }
}

是不是长的过分?OK,现在开始操作。

现在pom.xml中引入Lombok

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

引入完之后一定要记得Maven重新Import Changes
引入完之后一定要记得Maven重新Import Changes
引入完之后一定要记得Maven重新Import Changes


接下来,如果是Idea的用户,我们需要安装一个Lombok插件,才能有语法提示

lombok-plugins

OK,最后,在我们刚刚的那个实体上加code>@Data注解。意为自动生成GetterSettertoString等。然后愉快的把所有多余的代码删除吧。

代码:

@Entity
@DynamicUpdate//动态更新
@Data
public class ProductCategory {
    /**
     * 类目id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer categoryId;

    /**
     * 类目名字
     */
    private String categoryName;

    /**
     * 类目编号
     */
    private Integer categoryType;

    private  Date createTime;

    private  Date updateTime;

}

只有实体属性,非常干净。至于性能问题,lombok生成的GetterSetter等,是在编译期加入的,所以不影响性能。

声明:本文为原创作品,版权归作者所有。未经许可,不得转载或用于任何商业用途。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索