My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
BuiltInBindings  
More bindings that you can use
Updated Oct 16, 2011 by sberlin

Built-in Bindings

Alongside explicit and just-in-time bindings additional bindings are automatically included in the injector. Only the injector can create these bindings and attempting to bind them yourself is an error.

Loggers

Guice has a built-in binding for java.util.logging.Logger, intended to save some boilerplate. The binding automatically sets the logger's name to the name of the class into which the Logger is being injected..

@Singleton
public class ConsoleTransactionLog implements TransactionLog {

  private final Logger logger;

  @Inject
  public ConsoleTransactionLog(Logger logger) {
    this.logger = logger;
  }

  public void logConnectException(UnreachableException e) {
    /* the message is logged to the "ConsoleTransacitonLog" logger */
    logger.warning("Connect exception failed, " + e.getMessage());
  }

The Injector

In framework code, sometimes you don't know the type you need until runtime. In this rare case you should inject the injector. Code that injects the injector does not self-document its dependencies, so this approach should be done sparingly.

Providers

For every type Guice knows about, it can also inject a Provider of that type. Injecting Providers describes this in detail.

TypeLiterals

Guice has complete type information for everything it injects. If you're injecting parameterized types, you can inject a TypeLiteral<T> to reflectively tell you the element type.

The Stage

Guice supports a stage enum to differentiate between development and production runs.

MembersInjectors

When binding to providers or writing extensions, you may want Guice to inject dependencies into an object that you construct yourself. To do this, add a dependency on a MembersInjector<T> (where T is your object's type), and then call membersInjector.injectMembers(myNewObject).

Comment by peter.qu...@pq-solutions.de, Mar 3, 2010

Hi,

I just did not know how to inject class with generic type. Found the answer in the FAQ-Section. But I read this paragraph before and did not recognize that the information is already here. An example of how to use the TypeLiteral? would be very helpful.

Thanks.

Comment by miroslav...@gmail.com, Jun 17, 2010

TypeLiteral? is parameterised so one needs to create an anon new TypeLiteral?<Type>() instance as necessary.

Comment by sanrod...@gmail.com, Oct 2, 2010

There is an error here:

"ConsoleTransactionLog??" instead "ConsoleTransacitonLog?"

public void logConnectException(UnreachableException?? e) {

/ the message is logged to the "ConsoleTransacitonLog??" logger / logger.warning("Connect exception failed, " + e.getMessage()); }


Sign in to add a comment
Powered by Google Project Hosting