「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管理員
    暫無討論,說說你的看法吧