lombok
可以加在模型类上,帮助生成 get,set,toString,hashCode,equals等方法。
1) 在项目中添加 lombok 依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
2) 在编辑器上安装 lombok (安装包下载:https://pan.baidu.com/s/1e8K3sNATY56dYCqqLIoLpg)
- idea 插件
如果能联网,直接进入settings->plugins-> marketplace 搜索 lombok
不能联网,找到插件压缩包settings->plugins-> install plugin from disk3)在 application.properties 文件里写上
spring.datasource.initization-model=always
lombok 中常用标签
- @Data // 生成 get, set, toString, hashCode, equals
- @AllArgsConstructor // 根据所有的属性, 生成一个带参的构造方法
- @NoArgsConstructor // 生成一个无参构造
- @Builder // 生成一个建造器对象
- @Getter // 只生成 get方法
- @Setter // 只生成 set方法
- @Slf4j // 作用为当前的类生成一个日志对象
在 application.properties 文件里写上:logging.level.包名.启动springboot的类的类名=debug
代码演示
@Builder例子
@Builder public class Student { private int sid; private String sname; private Date birthday; private String sex; public static void main(String[] args) { Student stu = Student.builder().sid(1).sex("男").sname("张三").birthday(new Date()).build(); } }
结果
Student(sid=1, sname=张三, birthday=Sun Mar 03 20:37:36 CST 2019, sex=男)
@Slf4j 例子
@Service @Slf4j public class StudentService { // 使用 logback 通过 slf4j 这套接口间接调用 logback ,也就是日志 // 直接用 System.out 输出, 1. 性能损耗 2. 不能方便控制 public void add(int a, int b) { // 是否是 debug 的日志级别 if(log.isDebugEnabled()) { //用 log 的日志对象来记录日志 // 好处, 减少字符串拼接操作,字符串拼接如:System.out.println("a:" + a); log.debug("a:" + a); } // 另一种做法, 也可以避免字符串拼接操作 log.debug("b:{}" , b); } }
@Controller @Slf4j public class MyController { @Autowired private StudentService studentService; @RequestMapping("/add") @ResponseBody public void add() { studentService.add(10, 20); } }
结果
当浏览器上搜索 http://localhost:8080/add 时,服务器(浏览器)上输出
2019-03-03 20:59:17.423 DEBUG 6520 --- [nio-8080-exec-4] c.w.d.service.StudentService : a:10 2019-03-03 20:59:17.423 DEBUG 6520 --- [nio-8080-exec-4] c.w.d.service.StudentService : b:20
如果不想每个类上都加上 @Slf4j 才能使用日志,那么就在启动 spring boot 的类中添加 @Slf4j 标签在类上