3

In each controller I have in my Spring MVC webapp, there's this line:

static Logger logger = Logger.getLogger(ControllerName.class);

It's a little duplication. How can I write "logger-provided" controllers, without repeating this line every time?

Thanks

Fabio B.
  • 9,138
  • 25
  • 105
  • 177

2 Answers2

1

Maybe you don't like it, but one of the things I love about Project Lombok is this one. You can annotate your class with @Log4j (or better, @Slf4j) in order to get an invisible Logger called log.

sinuhepop
  • 20,010
  • 17
  • 72
  • 107
0

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());

}

Note that the logger is not longer static - this isn't really an issue with singleton Spring services/controllers, but still I find it a bit awkward. See also: Why do we declare Loggers static final?

Also it is a bit against OO principles and does not allow you to inherit from anything else. This is actually a limitation of a Java language, in Scala/ you can write:

class SomeController extends BaseController with Logging 

Where BaseController is a base class and Logging is a trait that mixes-in logger field to a SomeController class. Very convenient.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674