Why lombok?
lombok可以帮我们从实体类的getter、setter、constructor和toString等样板代码中解脱出来,使用lombok可以开发出更优雅的代码
1.maven依赖
<!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.14</version> <scope>provided</scope> </dependency>
2.常用注解
@Getter 生成get方法, @Setter 生成set方法, @AllArgsConstructor 生成所有属性的构造方法, @ToString 生成tostring方法, @Data 集合了前面几个注解的功能等
3.实例
为实体添加@AllArgsConstructor和@ToString注解
package com.zhya.entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; import java.util.Date; /** * 系统用户entity * * @Author zhangyang * @Date 下午 8:27 2018/11/20 0020 **/ @Getter @Setter @ToString @AllArgsConstructor public class SysUser implements Serializable { private static final long serialVersionUID = 2750888895274747017L; private String id; private String username; private Date addDate; private Date updateDate; }
测试使用实体的构造方法和toString方法
package com.zhya.controller; import com.zhya.entity.SysUser; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; /** * 系统用户controller * * @Author zhangyang * @Date 下午 8:31 2018/11/20 0020 **/ @RestController @RequestMapping("sysuser") public class SysUserController { /** * 获取单个系统用户 * * @Author zhangyang * @Date 下午 8:31 2018/11/20 0020 **/ @GetMapping("/{id}") public SysUser test(@PathVariable String id) { // FIXME for testing SysUser sysUser = new SysUser(id, "zhya", new Date(), new Date()); System.out.println(sysUser); return sysUser; } }