lony
lony

Reputation: 7770

How does the Built-in Bindings of Google Guice work?

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?

Upvotes: 1

Views: 830

Answers (2)

Kaleb Pederson
Kaleb Pederson

Reputation: 46479

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.

Upvotes: 2

Dave W. Smith
Dave W. Smith

Reputation: 24966

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.

Upvotes: 1

Related Questions