注解@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>IDE安裝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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM