转自:https://blog.csdn.net/qinxuefly/article/details/79159018
项目中经常使用bean,entity等类,绝大部分数据类类中都需要get、set、toString、equals和hashCode方法,虽然eclipse和idea开发环境下都有自动生成的快捷方式,但自动生成这些代码后,如果bean中的属性一旦有修改、删除或增加时,需要重新生成或删除get/set等方法,给代码维护增加负担。而使用了lombok则不一样,使用了lombok的注解(@Setter,@Getter,@ToString,@@RequiredArgsConstructor,@EqualsAndHashCode或@Data)之后,就不需要编写或生成get/set等方法,很大程度上减少了代码量,而且减少了代码维护的负担。故强烈建议项目中使用lombok,去掉bean中get、set、toString、equals和hashCode等方法的代码。
一、实战
1.安装lombok插件:
具体流程如图:
1.1
1.2
1.3
2.添加lombok的maven的pom.xml依赖:
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.16.10</version>
- </dependency>
3. 示例代码Student.java
- package com.lombok.demo;
- import lombok.EqualsAndHashCode;
- import lombok.Getter;
- import lombok.Setter;
- import lombok.ToString;
- /**
- * Created by zhangzh on 2017/2/8.
- */
- @Setter
- @Getter
- @ToString
- @EqualsAndHashCode
- public class Student {
- private String name;
- private int age;
- private String male;
- private String studentNo;
- }
4. 测试类LombokTest.java
- package com.lombok.demo;
- import lombok.extern.java.Log;
- /**
- * Created by zhangzh on 2017/2/8.
- */
- @Log
- public class LombokTest {
- public static void main(String[] args) {
- Student student = new Student();
- student.setAge(27);
- student.setMale("man");
- student.setName("lance");
- student.setStudentNo("2017");
- System.out.println(student.toString());
- Student student2 = new Student();
- student2.setAge(27);
- student2.setMale("man");
- student2.setName("lance");
- student2.setStudentNo("2017");
- System.out.println(student.equals(student2));
- student2.setStudentNo("2018");
- System.out.println(student.equals(student2));
- log.info("lombok test");
- }
- }
5. 输出结果:
- Student(name=lance, age=27, male=man, studentNo=2017)
- true
- false
- lombok test
另外@Data注解的作用相当于 @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode的合集。
另外@Log 省去了在LombokTest中添加 getLogger的如下代码:
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
看,简单吧!
- <pre code_snippet_id="2447922" snippet_file_name="blog_20170615_5_1108377"></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>