代码笔记

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

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插件,才能有语法提示

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等,是在编译期加入的,所以不影响性能。

Recent Posts

2023 年 WordPress 中最棒的多语言翻译插件推荐

担心如何翻译您的网站语言以支持…

12月 ago

2023 年 WordPress 中最棒的可视化页面构建器插件推荐

在设计任何页面或网站时,对于不…

12月 ago

Ella 多用途 Shopify 主题

Shopify 主题市场上有许…

12月 ago

AI Engine Pro

喵容今天带来的 AI Engi…

12月 ago

AIKit

喵容今天为您带来 AIKit …

12月 ago

AIomatic

喵容今天为您带来AIOmati…

12月 ago