Home > Back-end >  Use @Slf4j in a non-bean class
Use @Slf4j in a non-bean class

Time:01-28

Below is an example. What is the best way to inject the logger into a non-bean instance without passing it through a parameter since my project has a lot of non-bean classes deeply nested?

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SpringComponent {

    public String test() {
        log.info("method test called");
        A a = new A();
        a.run();
    }
}

public class A {

   public String run() {
        // I want to log here using Slf4j
    }
}

CodePudding user response:

If I am not wrong @Slf4j works on non bean classes as well. You can use it as shown below.

@Slf4j
public class A {

public String run() {
    log.info("logging works");
   }
}
  •  Tags:  
  • Related