idea中@Data标签getset不起作用 使用 lombok

spring cloud中使用@Data标签,不用手动添加get set方法,但是如果项目中其他类中使用getset方法,如果报错,原因是idea中没有添加Lombok插件,添加上插件便可以解决。截图如下

 

 

 

lombok是一款可以精减java代码、提升开发人员生产效率的辅助工具,利用注解在编译期自动生成setter/getter/toString()/constructor之类的代码。代码越少,意味着出bug的可能性越低。

 

对于 POJO, 我们需要为其中的每个字段生成 getter,setter 方法, 虽然能够使用 IDE 快速为我们生成. 但如果需要修改字段名称及字段类型, 那么就需要删除在重新进行生成, 终究还是有一些不方便. 如果使用 lombok, 可以通过一些简单的注解直接生成我们所需要的代码, 能极大的提高开发体验.

  1. 安装插件

     

    IDEA 安装 lombok.png

  2. 启用插件

     

    启用插件. png

  3. 在项目中使用

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.14</version>
        <scope>provided</scope>
    </dependency>
    
  4. lombok 常用注解介绍

    1. @NonNull

      使用 @NonNull 注解修饰的字段 通过 set 方法设置时如果为 null, 将抛出 NullPointerException

    2. @Cleanup

      主要用来修饰 IO 流相关类, 会在 finally 代码块中对该资源进行 close();

    3. @Getter,@Setter

      为字段生成 getter,setter 方法, 标记到类上表明为所有字段生成

    4. @ToString

      生成 toString 方法, 默认打印所有非静态字段

    5. @EqualsAndHashCode

      生成 equals 和 hashCode 方法

    6. @NoArgsConstructor,@RequiredArgsConstructor,@AllArgsConstructor

      NoArgsConstructor 无参构造函数
      RequiredArgsConstructor 为未初始化的 final 字段和使用 @NonNull 标注的字段生成构造函数
      AllArgsConstructor 为所有字段生成构造函数
      7. @Data
      > 相当于同时使用 @Getter,@Setter,@ToString,@EqualsAndHashCode,@RequiredArgsConstructor
      8. @Value
      > 使用后, 类将使用 final 进行修饰, 同时使用 @ToString,@EqualsAndHashCode,@AllArgsConstructor,@Getter

    7. @Builder

      创建一个静态内部类, 使用该类可以使用链式调用创建对象
      如 User 对象中存在 name,age 字段, User user=User.builder().name("姓名").age(20).build()
      10. @SneakyThrows
      > 对标注的方法进行 try catch 后抛出异常, 可在 value 输入需要 catch 的异常数组, 默认 catch Throwable

    8. @Synchronized

      在标注的方法内 使用 synchronized($lock) {} 对代码进行包裹 ,$lock 为 new Object[0]
      12. @Log,@CommonsLog,@JBossLog,@Log,@Log4j,@Log4j2,@Slf4j,@XSlf4j
      > 生成一个当前类的日志对象, 可以使用 topic 指定要获取的日志名称

  5. 自定义配置

    虽然 lombok 能为我们快速生成代码, 但是有一些生成的代码依然无法满足我们的需求. 此时可配置 lombok.config 来解决问题

    以下列出一些常用的配置

    lombok.getter.noIsPrefix=true(默认: false)  #lombok 默认对 boolean 类型字段生成的 get 方法使用 is 前缀, 通过此配置则使用 get 前缀
    lombok.accessors.chain=true(默认: false) #默认的 set 方法返回 void 设置为 true 返回调用对象本身
    lombok.accessors.fluent=true(默认: false) #如果设置为 true. get,set 方法将不带 get,set 前缀, 直接以字段名为方法名
    lombok.log.fieldName=logger(默认: log) #设置 log 类注解返回的字段名称
    

    ** 注 **: 在 IDEA 中,lombok.config 文件 请放置于 src\main\java 目录下, 在 src\main\resources 中将不生效

6、先来二段对比代码:

这是用lombok后的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

26

27

28

29

30

31

32

33

34

35

36

37

38

import lombok.*;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

import java.io.*;

import java.util.ArrayList;

 

@Data

@Slf4j

@AllArgsConstructor

public class Something {

 

    private String name;

    private final String country;

    private final Object lockObj = new Object();

 

    public void sayHello(@NonNull String target) {

        String content = String.format("hello,%s", target);

        System.out.println(content);

        log.info(content);

    }

 

    public void addBalabala() {

        val list = new ArrayList<String>();

        list.add("haha");

        System.out.println(list.size());

    }

 

    @SneakyThrows(IOException.class)

    public void closeBalabala() {

        @Cleanup InputStream is = new ByteArrayInputStream("hello world".getBytes());

        System.out.println(is.available());

    }

 

    @Synchronized("lockObj")

    public void lockMethod() {

        System.out.println("test lock method");

    }

}

等效于下面这段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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

import java.beans.ConstructorProperties;

import java.io.ByteArrayInputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Collections;

import lombok.NonNull;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

public class Something {

    private static final Logger log = LoggerFactory.getLogger(Something.class);

    private String name;

    private final String country;

    private final Object lockObj = new Object();

 

    public void sayHello(@NonNull String target) {

        if(target == null) {

            throw new NullPointerException("target");

        else {

            String content = String.format("hello,%s"new Object[]{target});

            System.out.println(content);

            log.info(content);

        }

    }

 

    public void addBalabala() {

        ArrayList list = new ArrayList();

        list.add("haha");

        System.out.println(list.size());

    }

 

    public void closeBalabala() {

        try {

            ByteArrayInputStream $ex = new ByteArrayInputStream("hello world".getBytes());

 

            try {

                System.out.println($ex.available());

            finally {

                if(Collections.singletonList($ex).get(0) != null) {

                    $ex.close();

                }

 

            }

 

        catch (IOException var6) {

            throw var6;

        }

    }

 

    public void lockMethod() {

        Object var1 = this.lockObj;

        synchronized(this.lockObj) {

            System.out.println("test lock method");

        }

    }

 

    public String getName() {

        return this.name;

    }

 

    public String getCountry() {

        return this.country;

    }

 

    public Object getLockObj() {

        return this.lockObj;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public boolean equals(Object o) {

        if(o == this) {

            return true;

        else if(!(o instanceof Something)) {

            return false;

        else {

            Something other = (Something)o;

            if(!other.canEqual(this)) {

                return false;

            else {

                label47: {

                    String this$name = this.getName();

                    String other$name = other.getName();

                    if(this$name == null) {

                        if(other$name == null) {

                            break label47;

                        }

                    else if(this$name.equals(other$name)) {

                        break label47;

                    }

 

                    return false;

                }

 

                String this$country = this.getCountry();

                String other$country = other.getCountry();

                if(this$country == null) {

                    if(other$country != null) {

                        return false;

                    }

                else if(!this$country.equals(other$country)) {

                    return false;

                }

 

                Object this$lockObj = this.getLockObj();

                Object other$lockObj = other.getLockObj();

                if(this$lockObj == null) {

                    if(other$lockObj != null) {

                        return false;

                    }

                else if(!this$lockObj.equals(other$lockObj)) {

                    return false;

                }

 

                return true;

            }

        }

    }

 

    protected boolean canEqual(Object other) {

        return other instanceof Something;

    }

 

    public int hashCode() {

        boolean PRIME = true;

        byte result = 1;

        String $name = this.getName();

        int result1 = result * 59 + ($name == null?0:$name.hashCode());

        String $country = this.getCountry();

        result1 = result1 * 59 + ($country == null?0:$country.hashCode());

        Object $lockObj = this.getLockObj();

        result1 = result1 * 59 + ($lockObj == null?0:$lockObj.hashCode());

        return result1;

    }

 

    public String toString() {

        return "Something(name=" this.getName() + ", country=" this.getCountry() + ", lockObj=" this.getLockObj() + ")";

    }

 

    @ConstructorProperties({"name""country"})

    public Something(String name, String country) {

        this.name = name;

        this.country = country;

    }

}

大概减少了2/3的代码,各种注解的详细用法,请参考:https://projectlombok.org/features/index.html

IDEA下使用时,可以通过插件的形式安装,插件下载地址:https://github.com/mplushnikov/lombok-intellij-plugin/releases 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值