@Slf4j使用

@Slf4j注解

介绍

常见的Slf4j日志打印有两种方式,分为传统方式和注解方式。

1、传统方式

示例:

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.service.HelloService;

@RestController
@RequestMapping("/Test")
public class HelloWorld {
    @Autowired
    private HelloService helloService;

    private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class);

    @GetMapping("/hello")
    public String sayHello(){
        logger.info("hello Sfl4j + logback......");
        return helloService.sayHello();
    }
}

2、注解方式

<1>maven依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<2>IDEA安装lombok插件

(如果注解@Slf4j注入后找不到变量log,那就给IDE安装lombok插件)

常用IDEA安装lombok插件,

Settings→Plugins→Browse repositories→lombok plugin

在线安装不行,采用本地安装,可以参考:

https://www.cnblogs.com/han-1034683568/p/9134980.html

<3>使用示例

package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.service.HelloService;

@Slf4j
@RestController
@RequestMapping("/Test")
public class HelloWorld {
    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String sayHello(){
        log.info("hello @Sfl4j + logback......");
        return helloService.sayHello();
    }
}

3、小结

注解方式较传统方式更加简单快捷,最直接的便利就是不用每次新建一个类时都要创建 logger,即:

 private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class);
发布了37 篇原创文章 · 获赞 7 · 访问量 1615

猜你喜欢

转载自blog.csdn.net/weixin_43862596/article/details/103026236