views:

147

answers:

2

Hello,

I tried Google Guice the first time and find it very nice. But, when I reached the part of Built-in Bindings I do not understand the examples.

For me it looks like I can use it for logging like an interceptor, but I don't know how.

Could someone of you explain this type of Binding and how I can use it? And maybe (if it's possible) use it for logging?

+1  A: 

All the example you point to is showing is that you don't have to provide a binding for Logger.class in code such as the example. Since the 99% case is

Logger logger = Logger.getLogger(ConsoleTransactionLog.class);

Guice will provide that logger for you as a convenience. If you need a different loggers (i.e., one not based on the class being injected into), you can provide your own binding.

Dave W. Smith
Maybe its a little bit foolish but could I ask you how I use THIS variant? I only know it like this (with a factory):private static final Log LOG = LogFactory.getLog(FrontLayer.class);and than use it withLOG.debug("bla");
lony
I don't know which Logging package you're using. Guice supports "built-in" support for java.util.logging.LoggerIf you're using a different logging package, you'll either need provide your own binding or somehow extend Guice.
Dave W. Smith
I normal use Apache Commons Logging in combination with log4j.
lony
+1  A: 

What the documentation indicates is that the bind(Logger.class).to(...) call has already been made for you. Thus, you don't need to call the bind method. Instead, you can inject it directly as if you had already called bind:

class DoSomething {
    private final Logger logger;
    @Inject public DoSomething(Logger logger) {
        this.logger = logger;
    }
}

Alternatively, you can get it from the injector:

/* even without specifying modules, logger is present */
Injector injector = Guice.createInjector();
Logger logger = injector.getInstance(Logger.class);

If you need to override the logger, then you'll have to use this method.

Kaleb Pederson
Thank! Thats what I want to know.
lony