Lombok簡介
Project Lombok makes java a spicier language by adding ‘handlers’ that know >how to build and compile simple, boilerplate-free, not-quite-java code.
github上官方是這麼描述lombok的:
lombok項目經過增長處理程序使咱們的java語言更加刺激(簡潔和快速)。
先看個簡單示例:
咱們作java開發的時候,最很多寫的就是javabean了,bean字段都須要添加gettter/setter方法,每每咱們只能一次又一次的使用ide生成gettter,setter 構造器等等。
lombok是如何幫咱們解決這種重複性勞動呢?javascript
- package com.lhy.boot.lombok;
- import lombok.Getter;
- import lombok.Setter;
- @Getter
- @Setter
- public class GetterSetterExample1 {
- private int age = 10;
- private String name ="張三丰";
- private boolean registerd;
- private String sex;
- }
編譯後的class:html
- package com.lhy.boot.lombok;
- public class GetterSetterExample1
- {
- private int age = 10;
- private String name = "張三丰";
- private boolean registerd;
- private String sex;
- public int getAge()
- {
- return this.age;
- }
- public String getName() {
- return this.name;
- }
- public boolean isRegisterd() {
- return this.registerd;
- }
- public String getSex() {
- return this.sex;
- }
- public GetterSetterExample1 setAge(int age) {
- this.age = age;
- return this;
- }
- public GetterSetterExample1 setName(String name) {
- this.name = name;
- return this;
- }
- public GetterSetterExample1 setRegisterd(boolean registerd) {
- this.registerd = registerd;
- return this;
- }
- public GetterSetterExample1 setSex(String sex) {
- this.sex = sex;
- return this;
- }
- }
經過gettter,setter註解lombok已經幫咱們自動生成了getter,setter方法!
是否是很神奇呢?lombok是怎麼的作到的?這個後邊再講,先把lombok ide插件環境搭起來java
下載並引用
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.16.16</version>
- </dependency>
或者到官網下載jar包 https://projectlombok.org/download
安裝ide插件
myeclipse/eclipse
下載完成後 命令行運行 jquery
- java -jar lombok-1.16.16.jar
specify location 選擇myeclipse安裝目錄,eclipse同理。android
點擊 install/update 安裝完成。git
或者將jar包放入myeclipse 根目錄下github
myeclipse.ini文件末尾添加:apache
- -javaagent:lombok-1.16.16.jar
安裝完畢後編程
打開myeclipse about 能夠看到api
證實插件安裝完成
IntelliJ IDEA
- 定位到 File > Settings > Plugins
- 點擊 Browse repositories…
- 搜索 Lombok Plugin
- 點擊 Install plugin
- 重啓 IDEA
Lombok註解詳解
全局配置文件
Lombok一般爲全部生成的節點生成註釋,添加@javax.annotation.Generated 。
能夠用:
lombok.addJavaxGeneratedAnnotation = false 設置取消
下面看下lombok提供了哪些有趣的註解。
1.@val @var
使用Lombok ,java也可以像javascript同樣使用弱類型定義變量了
val註解變量申明是final類型 var註解變量是非final類型
- import java.util.ArrayList;
- import java.util.HashMap;
- import lombok.val;
- public class ValExample {
- public String example() {
- val example = new ArrayList<String>();
- example.add("Hello, World!");
- val foo = example.get(0);
- return foo.toLowerCase();
- }
- public void example2() {
- val map = new HashMap<Integer, String>();
- map.put(0, "zero");
- map.put(5, "five");
- for (val entry : map.entrySet()) {
- System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
- }
- }
- }
- <span style="font-weight:normal;">import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Map;
- public class ValExample {
- public String example() {
- final ArrayList<String> example = new ArrayList<String>();
- example.add("Hello, World!");
- final String foo = example.get(0);
- return foo.toLowerCase();
- }
- public void example2() {
- final HashMap<Integer, String> map = new HashMap<Integer, String>();
- map.put(0, "zero");
- map.put(5, "five");
- for (final Map.Entry<Integer, String> entry : map.entrySet()) {
- System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
- }
- }
- }</span>
2.@NonNull
在方法或構造函數的參數上使用@NonNull,lombok將生成一個空值檢查語句。
- <span style="font-weight:normal;"> import lombok.NonNull;
- public class NonNullExample extends Something {
- private String name;
- public NonNullExample(@NonNull Person person) {
- super("Hello");
- this.name = person.getName();
- }
- }</span>
- <span style="font-weight:normal;">import lombok.NonNull;
- public class NonNullExample extends Something {
- private String name;
- public NonNullExample(@NonNull Person person) {
- super("Hello");
- if (person == null) {
- throw new NullPointerException("person");
- }
- this.name = person.getName();
- }
- }</span>
3.@Cleanup
使用該註解可以自動釋放io資源
- <span style="font-weight:normal;"> import lombok.Cleanup;
- import java.io.*;
- public class CleanupExample {
- 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[10000];
- while (true) {
- int r = in.read(b);
- if (r == -1) break;
- out.write(b, 0, r);
- }
- }
- }</span>
- <span style="font-weight:normal;">import java.io.*;
- public class CleanupExample {
- 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();
- }
- }
- }
- }</span>
固然從1.7開始jdk已經提供了try with resources的方式自動回收資源
- static String readFirstLineFromFile(String path) throws IOException {
- try (BufferedReader br = new BufferedReader(new FileReader(path))) {
- return br.readLine();
- }
- }
4.@Getter/@Setter
- <span style="font-weight:normal;">import lombok.AccessLevel;
- import lombok.Getter;
- import lombok.Setter;
- public class GetterSetterExample {
- /**
- * Age of the person. Water is wet.
- *
- * @param age New value for this person's age. Sky is blue.
- * @return The current value of this person's age. Circles are round.
- */
- @Getter @Setter private int age = 10;
- /**
- * Name of the person.
- * -- SETTER --
- * Changes the name of this person.
- *
- * @param name The new value.
- */
- @Setter(AccessLevel.PROTECTED) private String name;
- @Override public String toString() {
- return String.format("%s (age: %d)", name, age);
- }
- }</span>
- <span style="font-weight:normal;"> public class GetterSetterExample {
- /**
- * Age of the person. Water is wet.
- */
- private int age = 10;
- /**
- * Name of the person.
- */
- private String name;
- @Override public String toString() {
- return String.format("%s (age: %d)", name, age);
- }
- /**
- * Age of the person. Water is wet.
- *
- * @return The current value of this person's age. Circles are round.
- */
- public int getAge() {
- return age;
- }
- /**
- * Age of the person. Water is wet.
- *
- * @param age New value for this person's age. Sky is blue.
- */
- public void setAge(int age) {
- this.age = age;
- }
- /**
- * Changes the name of this person.
- *
- * @param name The new value.
- */
- protected void setName(String name) {
- this.name = name;
- }
- }</span>
lombok.accessors.chain
= [
true
|
false
] (default: false)若是設置爲true,生成的setter將返回this(而不是void),經過這個配置咱們能夠像jquery同樣愉快的鏈式編程了。能夠在類加增長一個@Accessors 註解 配置chain屬性,優先於全局配置。
lombok.accessors.fluent
= [
true
|
false
] (default: false)若是設置爲true,生成的getter和setter將不會使用bean標準的get、is或set進行前綴;相反,方法將使用與字段相同的名稱(減去前綴)。能夠在類加增長一個@Accessors註解,配置fluent屬性,優先於全局配置
lombok.accessors.prefix
+=
a field prefix (default: empty list)
給getter/setter方法增長前綴 例如配置 +=M 原有的 getFoo方法將變爲getMFoo方法。
lombok.getter.noIsPrefix
= [
true
|
false
] (default: false)
若是設置爲true,那麼boolean型字段生成的getter將使用get前綴而不是默認的is前綴
5.@ToString
生成一個toString方法,log debug神器
默認的toString格式爲:ClassName(fieldName= fieleValue ,fieldName1=fieleValue)
- <span style="font-weight:normal;">import lombok.ToString;
- @ToString(exclude="id")
- public class ToStringExample {
- private static final int STATIC_VAR = 10;
- private String name;
- private Shape shape = new Square(5, 10);
- private String[] tags;
- private int id;
- public String getName() {
- return this.getName();
- }
- @ToString(callSuper=true, includeFieldNames=true)
- public static class Square extends Shape {
- private final int width, height;
- public Square(int width, int height) {
- this.width = width;
- this.height = height;
- }
- }
- }</span>
- import java.util.Arrays;
- ublic class ToStringExample {
- private static final int STATIC_VAR = 10;
- private String name;
- private Shape shape = new Square(5, 10);
- private String[] tags;
- private int id;
- public String getName() {
- return this.getName();
- }
- public static class Square extends Shape {
- private final int width, height;
- public Square(int width, int height) {
- this.width = width;
- this.height = height;
- }
- @Override public String toString() {
- return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
- }
- }
- @Override public String toString() {
- return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
- }
擴展配置:
lombok.toString.includeFieldNames
= [true
| false
] (default: true)
一般,lombok以fieldName=fieldValue的形式爲每一個字段生成一個toString響應的片斷。若是設置爲false,lombok將省略字段的名稱,能夠在該註解上配置屬性includeFieldNames來標示包含的字段,這樣能夠覆蓋默認配置。
lombok.toString.doNotUseGetters
= [
true
|
false
] (default: false)
若是設置爲true,lombok將直接訪問字段,而不是在生成tostring方法時使用getter(若是可用)。能夠在該註解上配置屬性doNotUseGetters來標示不使用getter的字段,這樣能夠覆蓋默認配置。
6.@EqualsAndHashCode
給類增長equals和hashCode方法
- import lombok.EqualsAndHashCode;
- @EqualsAndHashCode(exclude={"id", "shape"})
- public class EqualsAndHashCodeExample {
- private transient int transientVar = 10;
- private String name;
- private double score;
- private Shape shape = new Square(5, 10);
- private String[] tags;
- private int id;
- public String getName() {
- return this.name;
- }
- @EqualsAndHashCode(callSuper=true)
- public static class Square extends Shape {
- private final int width, height;
- public Square(int width, int height) {
- this.width = width;
- this.height = height;
- }
- }
- }
- import java.util.Arrays;
- ublic class EqualsAndHashCodeExample {
- private transient int transientVar = 10;
- private String name;
- private double score;
- private Shape shape = new Square(5, 10);
- private String[] tags;
- private int id;
- public String getName() {
- return this.name;
- }
- @Override public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof EqualsAndHashCodeExample)) return false;
- EqualsAndHashCodeExample other = (EqualsAndHashCodeExample) o;
- if (!other.canEqual((Object)this)) return false;
- if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
- if (Double.compare(this.score, other.score) != 0) return false;
- if (!Arrays.deepEquals(this.tags, other.tags)) return false;
- return true;
- }
- @Override public int hashCode() {
- final int PRIME = 59;
- int result = 1;
- final long temp1 = Double.doubleToLongBits(this.score);
- result = (result*PRIME) + (this.name == null ? 43 : this.name.hashCode());
- result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
- result = (result*PRIME) + Arrays.deepHashCode(this.tags);
- return result;
- }
- protected boolean canEqual(Object other) {
- return other instanceof EqualsAndHashCodeExample;
- }
- public static class Square extends Shape {
- private final int width, height;
- public Square(int width, int height) {
- this.width = width;
- this.height = height;
- }
- @Override public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof Square)) return false;
- Square other = (Square) o;
- if (!other.canEqual((Object)this)) return false;
- if (!super.equals(o)) return false;
- if (this.width != other.width) return false;
- if (this.height != other.height) return false;
- return true;
- }
- @Override public int hashCode() {
- final int PRIME = 59;
- int result = 1;
- result = (result*PRIME) + super.hashCode();
- result = (result*PRIME) + this.width;
- result = (result*PRIME) + this.height;
- return result;
- }
- protected boolean canEqual(Object other) {
- return other instanceof Square;
- }
- }
擴展配置:
lombok.config增長:
lombok.equalsAndHashCode.doNotUseGetters
= [
true
|
false
] (default: false)若是設置爲true,lombok將直接訪問字段,而不是在生成equals和hashcode方法時使用getter(若是可用)。
能夠在該註解上配置屬性donotusegetter來標示不使用getter的字段,這樣能夠覆蓋默認配置。
lombok.equalsAndHashCode.callSuper
= [
call
|
skip
|
warn
] (default: warn)若是設置爲call,lombok將生成對hashCode的超類實現的調用。若是設置爲skip,則不會生成這樣的調用。默認行爲warn相似於skip,並帶有附加警告。
7.@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
給類增長無參構造器 指定參數的構造器 包含全部參數的構造器
- import lombok.AccessLevel;
- import lombok.RequiredArgsConstructor;
- import lombok.AllArgsConstructor;
- import lombok.NonNull;
- @RequiredArgsConstructor(staticName = "of")
- @AllArgsConstructor(access = AccessLevel.PROTECTED)
- public class ConstructorExample<T> {
- private int x, y;
- @NonNull private T description;
- @NoArgsConstructor
- public static class NoArgsExample {
- @NonNull private String field;
- }
- }
- public class ConstructorExample<T> {
- private int x, y;
- @NonNull private T description;
- private ConstructorExample(T description) {
- if (description == null) throw new NullPointerException("description");
- this.description = description;
- }
- public static <T> ConstructorExample<T> of(T description) {
- return new ConstructorExample<T>(description);
- }
- @java.beans.ConstructorProperties({"x", "y", "description"})
- protected ConstructorExample(int x, int y, T description) {
- if (description == null) throw new NullPointerException("description");
- this.x = x;
- this.y = y;
- this.description = description;
- }
- public static class NoArgsExample {
- @NonNull private String field;
- public NoArgsExample() {
- }
- }
- }
lombok.anyConstructor.suppressConstructorProperties
= [
true
|
false
] (default:
false
)若是將其設置爲true,那麼lombok將跳過添加一個@java.bean.ConstructorProperties生成的構造器。這在android和GWT開發中頗有用,由於這些註釋一般不可用。
8.@Data
包含如下註解的集合
@ToString,@EqualsAndHashCode,全部字段的 @Getter 全部非final字段的@Setter ,@RequiredArgsConstructor
- import lombok.AccessLevel;
- import lombok.Setter;
- import lombok.Data;
- import lombok.ToString;
- @Data public class DataExample {
- private final String name;
- @Setter(AccessLevel.PACKAGE) private int age;
- private double score;
- private String[] tags;
- @ToString(includeFieldNames=true)
- @Data(staticConstructor="of")
- public static class Exercise<T> {
- private final String name;
- private final T value;
- }
- }
翻譯後
- import java.util.Arrays;
- public class DataExample {
- private final String name;
- private int age;
- private double score;
- private String[] tags;
- public DataExample(String name) {
- this.name = name;
- }
- public String getName() {
- return this.name;
- }
- void setAge(int age) {
- this.age = age;
- }
- public int getAge() {
- return this.age;
- }
- public void setScore(double score) {
- this.score = score;
- }
- public double getScore() {
- return this.score;
- }
- public String[] getTags() {
- return this.tags;
- }
- public void setTags(String[] tags) {
- this.tags = tags;
- }
- @Override public String toString() {
- return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
- }
- protected boolean canEqual(Object other) {
- return other instanceof DataExample;
- }
- @Override public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof DataExample)) return false;
- DataExample other = (DataExample) o;
- if (!other.canEqual((Object)this)) return false;
- if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
- if (this.getAge() != other.getAge()) return false;
- if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
- if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
- return true;
- }
- @Override public int hashCode() {
- final int PRIME = 59;
- int result = 1;
- final long temp1 = Double.doubleToLongBits(this.getScore());
- result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
- result = (result*PRIME) + this.getAge();
- result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
- result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
- return result;
- }
- public static class Exercise<T> {
- private final String name;
- private final T value;
- private Exercise(String name, T value) {
- this.name = name;
- this.value = value;
- }
- public static <T> Exercise<T> of(String name, T value) {
- return new Exercise<T>(name, value);
- }
- public String getName() {
- return this.name;
- }
- public T getValue() {
- return this.value;
- }
- @Override public String toString() {
- return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
- }
- protected boolean canEqual(Object other) {
- return other instanceof Exercise;
- }
- @Override public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof Exercise)) return false;
- Exercise<?> other = (Exercise<?>) o;
- if (!other.canEqual((Object)this)) return false;
- if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;
- if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;
- return true;
- }
- @Override public int hashCode() {
- final int PRIME = 59;
- int result = 1;
- result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
- result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());
- return result;
- }
- }
- }
9.@Value
@value是@data的不可變對象 (不可變對象的用處和建立:https://my.oschina.net/jasonultimate/blog/166810)
全部字段都是私有的,默認狀況下是final的,而且不會生成setter。默認狀況下,類自己也是final的,由於不可變性不能強制轉化爲子類。與@data同樣,有用toString()、equals()和hashCode()方法也是生成的,每一個字段都有一個getter方法,而且一個覆蓋每一個參數的構造器也會生成。
10.@Builder
建築者模式
是如今比較推崇的一種構建值對象的方式。
- import lombok.Builder;
- import lombok.Singular;
- import java.util.Set;
- @Builder
- public class BuilderExample {
- private String name;
- private int age;
- @Singular private Set<String> occupations;
- }
- import java.util.Set;
- public class BuilderExample {
- private String name;
- private int age;
- private Set<String> occupations;
- BuilderExample(String name, int age, Set<String> occupations) {
- this.name = name;
- this.age = age;
- this.occupations = occupations;
- }
- public static BuilderExampleBuilder builder() {
- return new BuilderExampleBuilder();
- }
- public static class BuilderExampleBuilder {
- private String name;
- private int age;
- private java.util.ArrayList<String> occupations;
- BuilderExampleBuilder() {
- }
- public BuilderExampleBuilder name(String name) {
- this.name = name;
- return this;
- }
- public BuilderExampleBuilder age(int age) {
- this.age = age;
- return this;
- }
- public BuilderExampleBuilder occupation(String occupation) {
- if (this.occupations == null) {
- this.occupations = new java.util.ArrayList<String>();
- }
- this.occupations.add(occupation);
- return this;
- }
- public BuilderExampleBuilder occupations(Collection<? extends String> occupations) {
- if (this.occupations == null) {
- this.occupations = new java.util.ArrayList<String>();
- }
- this.occupations.addAll(occupations);
- return this;
- }
- public BuilderExampleBuilder clearOccupations() {
- if (this.occupations != null) {
- this.occupations.clear();
- }
- return this;
- }
- public BuilderExample build() {
- // complicated switch statement to produce a compact properly sized immutable set omitted.
- // go to https://projectlombok.org/features/Singular-snippet.html to see it.
- Set<String> occupations = ...;
- return new BuilderExample(name, age, occupations);
- }
- @java.lang.Override
- public String toString() {
- return "BuilderExample.BuilderExampleBuilder(name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")";
- }
- }
- }
11.@SneakyThrows
把checked異常轉化爲unchecked異常,好處是不用再往上層方法拋出了,美其名曰暗埋異常
- import lombok.SneakyThrows;
- public class SneakyThrowsExample implements Runnable {
- @SneakyThrows(UnsupportedEncodingException.class)
- public String utf8ToString(byte[] bytes) {
- return new String(bytes, "UTF-8");
- }
- @SneakyThrows
- public void run() {
- throw new Throwable();
- }
- }
- import lombok.Lombok;
- public class SneakyThrowsExample implements Runnable {
- public String utf8ToString(byte[] bytes) {
- try {
- return new String(bytes, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- throw Lombok.sneakyThrow(e);
- }
- }
- public void run() {
- try {
- throw new Throwable();
- } catch (Throwable t) {
- throw Lombok.sneakyThrow(t);
- }
- }
- }
12.@Synchronized
相似於Synchronized 關鍵字 可是能夠隱藏同步鎖
- import lombok.Synchronized;
- ublic class SynchronizedExample {
- 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");
- }
- public class SynchronizedExample {
- 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");
- }
- }
- }
xianzjdk推薦使用Lock了,這個僅供參考
13.@Getter(lazy=true)
若是getter方法計算值須要大量CPU,或者值佔用大量內存,第一次調用這個getter,它將一次計算一個值,而後從那時開始緩存它
- import lombok.Getter;
- public class GetterLazyExample {
- @Getter(lazy=true) private final double[] cached = expensive();
- private double[] expensive() {
- double[] result = new double[1000000];
- for (int i = 0; i < result.length; i++) {
- result[i] = Math.asin(i);
- }
- return result;
- }
- }
- public class GetterLazyExample {
- private final java.util.concurrent.AtomicReference<java.lang.Object> cached = new java.util.concurrent.AtomicReference<java.lang.Object>();
- public double[] getCached() {
- java.lang.Object value = this.cached.get();
- if (value == null) {
- synchronized(this.cached) {
- value = this.cached.get();
- if (value == null) {
- final double[] actualValue = expensive();
- value = actualValue == null ? this.cached : actualValue;
- this.cached.set(value);
- }
- }
- }
- return (double[])(value == this.cached ? null : value);
- }
- private double[] expensive() {
- double[] result = new double[1000000];
- for (int i = 0; i < result.length; i++) {
- result[i] = Math.asin(i);
- }
- return result;
- }
14.@Log
能夠生成各類log對象,方便多了
- import lombok.extern.java.Log;
- import lombok.extern.slf4j.Slf4j;
- @Log
- public class LogExample {
- public static void main(String... args) {
- log.error("Something's wrong here");
- }
- }
- @Slf4j
- public class LogExampleOther {
- public static void main(String... args) {
- log.error("Something else is wrong here");
- }
- }
- @CommonsLog(topic="CounterLog")
- public class LogExampleCategory {
- public static void main(String... args) {
- log.error("Calling the 'CounterLog' with a message");
- }
- }
- public class LogExample {
- private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
- public static void main(String... args) {
- log.error("Something's wrong here");
- }
- }
- public class LogExampleOther {
- private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);
- public static void main(String... args) {
- log.error("Something else is wrong here");
- }
- }
- public class LogExampleCategory {
- private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog");
- public static void main(String... args) {
- log.error("Calling the 'CounterLog' with a message");
- }
- }
全部支持的log類型:
@CommonsLog
Creates
private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
@JBossLog
Creates
private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LogExample.class);
@Log
Creates
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
@Log4j
Creates
private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class);
@Log4j2
Creates
private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
@Slf4j
Creates
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
@XSlf4j
Creates
private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
擴展配置:
lombok.log.fieldName
=
an identifier
(default:
log
).生成log字段的名稱 默認爲log
lombok.log.fieldIsStatic
= [
true
|
false
] (default: true)生成log是不是static的 默認爲static
官方文檔說明:https://projectlombok.org/features/all
Lombok原理
![](http://static.javashuo.com/static/loading.gif)
1)javac對源代碼進行分析,生成一棵抽象語法樹(AST)
2)運行過程當中調用實現了"JSR 269 API"的lombok程序
3)此時lombok就對第一步驟獲得的AST進行處理,找到@Data註解所在類對應的語法樹(AST),而後修改該語法樹(AST),增長getter和setter方法定義的相應樹節點
4)javac使用修改後的抽象語法樹(AST)生成字節碼文件,即給class增長新的節點(代碼塊)
ide中使用Lombok的注意事項
1.項目中要使用lombok 不只ide要支持(不然一堆錯誤),項目中也要引入jar包
2.若是配置lombok.config文件,修改文件的屬性值後,並不會自動從新編譯class文件,ide編輯器也不會自動更新,全部每次修改配置文件後最後關閉java文件窗口從新打開,而且clean下項目