lombok有什么用
在我們實體bean中有大量的getter/setter方法以及tostring, hashcode等可能不會用到,但是某些時候仍然需要復寫;在使用lombok之后,將由其來自動幫你實現代碼生成。注意,其是在編譯源碼過程中,幫你自動生成的。就是說,將極大減少你的代碼總量。
lombok的官方地址:https://projectlombok.org/
使用lombok時需要注意的點
- 在類需要序列化、反序列化時或者需要詳細控制字段時,應該謹慎考慮是否要使用lombok,因為在這種情況下容易出問題。例如:jackson、json序列化
- 使用lombok雖然能夠省去手動創建setter和getter方法等繁瑣事情,但是卻降低了源代碼文件的可讀性和完整性,減低了閱讀源代碼的舒適度
- 使用@slf4j還是@log4j注解,需要根據實際項目中使用的日志框架來選擇。
- lombok并非處處適用,我們需要選擇適合的地方使用lombok,例如pojo是一個好地方,因為pojo很單純
lombok的安裝
eclipse安裝lombok步驟:
下載最新的lombok.jar包,下載地址:https://projectlombok.org/download.html
進入cmd窗口,切到lombok下載的目錄,運行命令: java -jar lombok.jar,會出現如下界面:
已經默認選好了eclipse安裝目錄(這個可能是因為我只有一個盤,如果沒有默認選擇,可以自己點擊下方specify location...按鈕選擇eclipse安裝目錄),點擊圖中紅色箭頭指向的按鈕,即可完成安裝。成功界面如下:
eclipse安裝目錄下的eclipse.ini文件末尾已經加了一行內容(這個路徑因人而異,和eclipse安裝目錄有關),如下:
而且安裝目錄下也多了一個lombok.jar
spring boot集成lombok
先去http://start.spring.io/在線生成一個spring boot項目腳手架,導入eclipse。
在pom.xml里添加lombok依賴:
1
2
3
4
5
|
<dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <version> 1.16 . 14 </version> </dependency> |
在src/main/java/com/example/springbootlombok/entity下新建一個student.java的java bean:
1
2
3
4
5
6
7
8
9
|
package com.example.springbootlombok.entity; import lombok.data; @data public class student { private string name; private int age; } |
在src/test/java/com/example/springbootlombok下新建一個testentity.java的測試類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package com.example.springbootlombok; import org.junit.test; import org.junit.runner.runwith; import org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4.springrunner; import com.example.springbootlombok.entity.student; import lombok.extern.slf4j.slf4j; @runwith (springrunner. class ) @springboottest @slf4j public class testentity { student student = new student(); @test public void test() { student.setname( "張三" ); student.setage( 12 ); log.info( "測試結果:" + student.tostring()); } } |
執行junit測試,成功的話,日志里會有打印測試結果:student(name=張三, age=12),至此,spring boot已經成功集成lombok了。
lombok常用注解
@nonnull
這個注解可以用在成員方法或者構造方法的參數前面,會自動產生一個關于此參數的非空檢查,如果參數為空,則拋出一個空指針異常,舉個例子:
編譯前的代碼:
1
2
3
4
|
//成員方法參數加上@nonnull注解 public string getname( @nonnull person p) { return p.getname(); } |
編譯后的代碼:
1
2
3
4
5
6
|
public string getname( @nonnull person p) { if (p == null ) { throw new nullpointerexception( "person" ); } return p.getname(); } |
@cleanup
這個注解用在變量前面,可以保證此變量代表的資源會被自動關閉,默認是調用資源的close()方法,如果該資源有其它關閉方法,可使用@cleanup("methodname")來指定要調用的方法,就用輸入輸出流來舉個例子:
編譯前的代碼:
1
2
3
4
5
6
7
8
9
10
|
public static void main(string[] args) throws ioexception { @cleanup inputstream in = new fileinputstream(args[ 0 ]); @cleanup outputstream out = new fileoutputstream(args[ 1 ]); byte [] b = new byte [ 1024 ]; while ( true ) { int r = in.read(b); if (r == - 1 ) break ; out.write(b, 0 , r); } } |
編譯后的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public static void main(string[] args) throws ioexception { inputstream in = new fileinputstream(args[ 0 ]); try { outputstream out = new fileoutputstream(args[ 1 ]); try { byte [] b = new byte [ 10000 ]; while ( true ) { int r = in.read(b); if (r == - 1 ) break ; out.write(b, 0 , r); } } finally { if (out != null ) { out.close(); } } } finally { if (in != null ) { in.close(); } } } |
@getter/@setter
這一對注解從名字上就很好理解,用在成員變量前面,相當于為成員變量生成對應的get和set方法,同時還可以為生成的方法指定訪問修飾符,當然,默認為public,直接來看下面的簡單的例子:
編譯前的代碼:
1
2
3
4
5
6
7
8
9
10
11
|
public class programmer { @getter @setter private string name; @setter (accesslevel. protected ) private int age; @getter (accesslevel. public ) private string language; } |
編譯后的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class programmer { private string name; private int age; private string language; public void setname(string name) { this .name = name; } public string getname() { return name; } protected void setage( int age) { this .age = age; } public string getlanguage() { return language; } } |
這兩個注解還可以直接用在類上,可以為此類里的所有非靜態成員變量生成對應的get和set方法。
@getter(lazy=true)
如果bean的一個字段的初始化是代價比較高的操作,比如加載大量的數據;同時這個字段并不是必定使用的。那么使用懶加載機制,可以保證節省資源。
懶加載機制,是對象初始化時,該字段并不會真正的初始化,而是第一次訪問該字段時才進行初始化字段的操作。
@tostring/@equalsandhashcode
這兩個注解也比較好理解,就是生成tostring,equals和hashcode方法,同時后者還會生成一個canequal方法,用于判斷某個對象是否是當前類的實例,生成方法時只會使用類中的非靜態和非transient成員變量,這些都比較好理解,就不舉例子了。
當然,這兩個注解也可以添加限制條件,例如用@tostring(exclude={"param1","param2"})來排除param1和param2兩個成員變量,或者用@tostring(of={"param1","param2"})來指定使用param1和param2兩個成員變量,@equalsandhashcode注解也有同樣的用法。
@noargsconstructor/@requiredargsconstructor /@allargsconstructor
這三個注解都是用在類上的,第一個和第三個都很好理解,就是為該類產生無參的構造方法和包含所有參數的構造方法,第二個注解則使用類中所有帶有@nonnull注解的或者帶有final修飾的成員變量生成對應的構造方法。當然,和前面幾個注解一樣,成員變量都是非靜態的,另外,如果類中含有final修飾的成員變量,是無法使用@noargsconstructor注解的。
三個注解都可以指定生成的構造方法的訪問權限,同時,第二個注解還可以用@requiredargsconstructor(staticname="methodname")
的形式生成一個指定名稱的靜態方法,返回一個調用相應的構造方法產生的對象,下面來看一個生動鮮活的例子:
編譯前的代碼:
1
2
3
4
5
6
7
8
9
10
|
@requiredargsconstructor (staticname = "sunsfan" ) @allargsconstructor (access = accesslevel. protected ) @noargsconstructor public class shape { private int x; @nonnull private double y; @nonnull private string name; } |
編譯后的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class shape { private int x; private double y; private string name; public shape() { } protected shape( int x, double y, string name) { this .x = x; this .y = y; this .name = name; } public shape( double y, string name) { this .y = y; this .name = name; } public static shape sunsfan( double y, string name) { return new shape(y, name); } } |
@data/@value
@data注解綜合了@getter/@setter,@tostring,@equalsandhashcode和@requiredargsconstructor注解,其中@requiredargsconstructor使用了類中的帶有@nonnull注解的或者final修飾的成員變量,它可以使用@data(staticconstructor="methodname")來生成一個靜態方法,返回一個調用相應的構造方法產生的對象。
@value注解和@data類似,區別在于它會把所有成員變量默認定義為private final修飾,并且不會生成set方法。
@sneakythrows
這個注解用在方法上,可以將方法中的代碼用try-catch語句包裹起來,捕獲異常并在catch中用lombok.sneakythrow(e)把異常拋出,可以使用@sneakythrows(exception.class)的形式指定拋出哪種異常,很簡單的注解,直接看個例子:
編譯前的代碼:
1
2
3
4
5
6
7
8
9
10
11
|
public class sneakythrows implements runnable { @sneakythrows (unsupportedencodingexception. class ) public string utf8tostring( byte [] bytes) { return new string(bytes, "utf-8" ); } @sneakythrows public void run() { throw new throwable(); } } |
編譯后的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class sneakythrows implements runnable { @sneakythrows (unsupportedencodingexception. class ) public string utf8tostring( byte [] bytes) { try { return new string(bytes, "utf-8" ); } catch (unsupportedencodingexception uee) { throw lombok.sneakythrow(uee); } } @sneakythrows public void run() { try { throw new throwable(); } catch (throwable t) { throw lombok.sneakythrow(t); } } } |
@synchronized
這個注解用在類方法或者實例方法上,效果和synchronized關鍵字相同,區別在于鎖對象不同,對于類方法和實例方法,synchronized關鍵字的鎖對象分別是類的class對象和this對象,而@synchronized的鎖對象分別是私有靜態final對象lock和私有final對象lock,當然,也可以自己指定鎖對象,例子也很簡單,往下看:
編譯前的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class synchronized { private final object readlock = new object(); @synchronized public static void hello() { system.out.println( "world" ); } @synchronized public int answertolife() { return 42 ; } @synchronized ( "readlock" ) public void foo() { system.out.println( "bar" ); } } |
編譯后的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class synchronized { private static final object $lock = new object[ 0 ]; private final object $lock = new object[ 0 ]; private final object readlock = new object(); public static void hello() { synchronized ($lock) { system.out.println( "world" ); } } public int answertolife() { synchronized ($lock) { return 42 ; } } public void foo() { synchronized (readlock) { system.out.println( "bar" ); } } } |
@log
這個注解用在類上,可以省去從日志工廠生成日志對象這一步,直接進行日志記錄,具體注解根據日志工具的不同而不同,同時,可以在注解中使用topic來指定生成log對象時的類名。不同的日志注解總結如下(上面是注解,下面是編譯后的代碼):
@commonslog
==> private static final org.apache.commons.logging.log log = org.apache.commons.logging.logfactory.getlog(logexample.class);@jbosslog
==> private static final org.jboss.logging.logger log = org.jboss.logging.logger.getlogger(logexample.class);@log
==> private static final java.util.logging.logger log = java.util.logging.logger.getlogger(logexample.class.getname());@log4j
==> private static final org.apache.log4j.logger log = org.apache.log4j.logger.getlogger(logexample.class);@log4j2
==> private static final org.apache.logging.log4j.logger log = org.apache.logging.log4j.logmanager.getlogger(logexample.class);@slf4j
==> private static final org.slf4j.logger log = org.slf4j.loggerfactory.getlogger(logexample.class);@xslf4j
==> private static final org.slf4j.ext.xlogger log = org.slf4j.ext.xloggerfactory.getxlogger(logexample.class);
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000018528777