lombok有什么用
在我們實(shí)體bean中有大量的getter/setter方法以及tostring, hashcode等可能不會(huì)用到,但是某些時(shí)候仍然需要復(fù)寫(xiě);在使用lombok之后,將由其來(lái)自動(dòng)幫你實(shí)現(xiàn)代碼生成。注意,其是在編譯源碼過(guò)程中,幫你自動(dòng)生成的。就是說(shuō),將極大減少你的代碼總量。
lombok的官方地址:https://projectlombok.org/
使用lombok時(shí)需要注意的點(diǎn)
- 在類(lèi)需要序列化、反序列化時(shí)或者需要詳細(xì)控制字段時(shí),應(yīng)該謹(jǐn)慎考慮是否要使用lombok,因?yàn)樵谶@種情況下容易出問(wèn)題。例如:jackson、json序列化
- 使用lombok雖然能夠省去手動(dòng)創(chuàng)建setter和getter方法等繁瑣事情,但是卻降低了源代碼文件的可讀性和完整性,減低了閱讀源代碼的舒適度
- 使用@slf4j還是@log4j注解,需要根據(jù)實(shí)際項(xiàng)目中使用的日志框架來(lái)選擇。
- lombok并非處處適用,我們需要選擇適合的地方使用lombok,例如pojo是一個(gè)好地方,因?yàn)閜ojo很單純
lombok的安裝
eclipse安裝lombok步驟:
下載最新的lombok.jar包,下載地址:https://projectlombok.org/download.html
進(jìn)入cmd窗口,切到lombok下載的目錄,運(yùn)行命令: java -jar lombok.jar,會(huì)出現(xiàn)如下界面:
已經(jīng)默認(rèn)選好了eclipse安裝目錄(這個(gè)可能是因?yàn)槲抑挥幸粋€(gè)盤(pán),如果沒(méi)有默認(rèn)選擇,可以自己點(diǎn)擊下方specify location...按鈕選擇eclipse安裝目錄),點(diǎn)擊圖中紅色箭頭指向的按鈕,即可完成安裝。成功界面如下:
eclipse安裝目錄下的eclipse.ini文件末尾已經(jīng)加了一行內(nèi)容(這個(gè)路徑因人而異,和eclipse安裝目錄有關(guān)),如下:
而且安裝目錄下也多了一個(gè)lombok.jar
spring boot集成lombok
先去http://start.spring.io/在線生成一個(gè)spring boot項(xiàng)目腳手架,導(dǎo)入eclipse。
在pom.xml里添加lombok依賴(lài):
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下新建一個(gè)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下新建一個(gè)testentity.java的測(cè)試類(lèi):
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( "測(cè)試結(jié)果:" + student.tostring()); } } |
執(zhí)行junit測(cè)試,成功的話,日志里會(huì)有打印測(cè)試結(jié)果:student(name=張三, age=12),至此,spring boot已經(jīng)成功集成lombok了。
lombok常用注解
@nonnull
這個(gè)注解可以用在成員方法或者構(gòu)造方法的參數(shù)前面,會(huì)自動(dòng)產(chǎn)生一個(gè)關(guān)于此參數(shù)的非空檢查,如果參數(shù)為空,則拋出一個(gè)空指針異常,舉個(gè)例子:
編譯前的代碼:
1
2
3
4
|
//成員方法參數(shù)加上@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
這個(gè)注解用在變量前面,可以保證此變量代表的資源會(huì)被自動(dòng)關(guān)閉,默認(rèn)是調(diào)用資源的close()方法,如果該資源有其它關(guān)閉方法,可使用@cleanup("methodname")來(lái)指定要調(diào)用的方法,就用輸入輸出流來(lái)舉個(gè)例子:
編譯前的代碼:
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
這一對(duì)注解從名字上就很好理解,用在成員變量前面,相當(dāng)于為成員變量生成對(duì)應(yīng)的get和set方法,同時(shí)還可以為生成的方法指定訪問(wèn)修飾符,當(dāng)然,默認(rèn)為public,直接來(lái)看下面的簡(jiǎn)單的例子:
編譯前的代碼:
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; } } |
這兩個(gè)注解還可以直接用在類(lèi)上,可以為此類(lèi)里的所有非靜態(tài)成員變量生成對(duì)應(yīng)的get和set方法。
@getter(lazy=true)
如果bean的一個(gè)字段的初始化是代價(jià)比較高的操作,比如加載大量的數(shù)據(jù);同時(shí)這個(gè)字段并不是必定使用的。那么使用懶加載機(jī)制,可以保證節(jié)省資源。
懶加載機(jī)制,是對(duì)象初始化時(shí),該字段并不會(huì)真正的初始化,而是第一次訪問(wèn)該字段時(shí)才進(jìn)行初始化字段的操作。
@tostring/@equalsandhashcode
這兩個(gè)注解也比較好理解,就是生成tostring,equals和hashcode方法,同時(shí)后者還會(huì)生成一個(gè)canequal方法,用于判斷某個(gè)對(duì)象是否是當(dāng)前類(lèi)的實(shí)例,生成方法時(shí)只會(huì)使用類(lèi)中的非靜態(tài)和非transient成員變量,這些都比較好理解,就不舉例子了。
當(dāng)然,這兩個(gè)注解也可以添加限制條件,例如用@tostring(exclude={"param1","param2"})來(lái)排除param1和param2兩個(gè)成員變量,或者用@tostring(of={"param1","param2"})來(lái)指定使用param1和param2兩個(gè)成員變量,@equalsandhashcode注解也有同樣的用法。
@noargsconstructor/@requiredargsconstructor /@allargsconstructor
這三個(gè)注解都是用在類(lèi)上的,第一個(gè)和第三個(gè)都很好理解,就是為該類(lèi)產(chǎn)生無(wú)參的構(gòu)造方法和包含所有參數(shù)的構(gòu)造方法,第二個(gè)注解則使用類(lèi)中所有帶有@nonnull注解的或者帶有final修飾的成員變量生成對(duì)應(yīng)的構(gòu)造方法。當(dāng)然,和前面幾個(gè)注解一樣,成員變量都是非靜態(tài)的,另外,如果類(lèi)中含有final修飾的成員變量,是無(wú)法使用@noargsconstructor注解的。
三個(gè)注解都可以指定生成的構(gòu)造方法的訪問(wèn)權(quán)限,同時(shí),第二個(gè)注解還可以用@requiredargsconstructor(staticname="methodname")
的形式生成一個(gè)指定名稱(chēng)的靜態(tài)方法,返回一個(gè)調(diào)用相應(yīng)的構(gòu)造方法產(chǎn)生的對(duì)象,下面來(lái)看一個(gè)生動(dòng)鮮活的例子:
編譯前的代碼:
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使用了類(lèi)中的帶有@nonnull注解的或者final修飾的成員變量,它可以使用@data(staticconstructor="methodname")來(lái)生成一個(gè)靜態(tài)方法,返回一個(gè)調(diào)用相應(yīng)的構(gòu)造方法產(chǎn)生的對(duì)象。
@value注解和@data類(lèi)似,區(qū)別在于它會(huì)把所有成員變量默認(rèn)定義為private final修飾,并且不會(huì)生成set方法。
@sneakythrows
這個(gè)注解用在方法上,可以將方法中的代碼用try-catch語(yǔ)句包裹起來(lái),捕獲異常并在catch中用lombok.sneakythrow(e)把異常拋出,可以使用@sneakythrows(exception.class)的形式指定拋出哪種異常,很簡(jiǎn)單的注解,直接看個(gè)例子:
編譯前的代碼:
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
這個(gè)注解用在類(lèi)方法或者實(shí)例方法上,效果和synchronized關(guān)鍵字相同,區(qū)別在于鎖對(duì)象不同,對(duì)于類(lèi)方法和實(shí)例方法,synchronized關(guān)鍵字的鎖對(duì)象分別是類(lèi)的class對(duì)象和this對(duì)象,而@synchronized的鎖對(duì)象分別是私有靜態(tài)final對(duì)象lock和私有final對(duì)象lock,當(dāng)然,也可以自己指定鎖對(duì)象,例子也很簡(jiǎn)單,往下看:
編譯前的代碼:
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
這個(gè)注解用在類(lèi)上,可以省去從日志工廠生成日志對(duì)象這一步,直接進(jìn)行日志記錄,具體注解根據(jù)日志工具的不同而不同,同時(shí),可以在注解中使用topic來(lái)指定生成log對(duì)象時(shí)的類(lèi)名。不同的日志注解總結(jié)如下(上面是注解,下面是編譯后的代碼):
@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);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000018528777