Log4j in Spring mvc controllers: how to remove duplication
You might not like it, but one of the things I love about Project Lombok is. You can annotate your class with @ Log4j (or better, @ Slf4j) to get an invisible Logger named log .
source to share
The first suggestion is to have a common base class for all controllers with the following line:
public abstract class AbstractBaseController {
protected Logger logger = Logger.getLogger(this.getClass());
}
Please note that the logger is no longer static
- this is not a problem with singleton Spring services / controllers, but still I find it a little awkward. See Also: Why Are We Declaring Static Loggers Finalists?
Also it goes against OO principles a bit and doesn't let you inherit anything else. This is actually a limitation of the Java language, in Scala /slf4s You can write:
class SomeController extends BaseController with Logging
Where BaseController
is the base class, and Logging
is the property that is mixed in the logger
field with the class SomeController
. Very comfortably.
source to share