Provider

Create a Guice Provider that programmatically creates a Database instance.

Example 1

Example provider implementation using DatabaseConfig and DatabaseFactory.

import io.ebean.DB;
import io.ebean.Database;
import com.google.inject.Provider;

public class DatabaseProvider implements Provider<Database> {

  @Override
  public Database get() {

    DatabaseConfig config = new DatabaseConfig();
    ...
    // plus any programmatic configuration

    return DatabaseFactory.create(config);
  }
}

Example 2

Example provider implementation using DB that implicitly creates the default Database using application.yaml.

import io.ebean.DB;
import io.ebean.Database;
import com.google.inject.Provider;

public class DatabaseProvider implements Provider<Database> {

  @Override
  public Database get() {

    // Database configured by application.properties
    return DB.getDefault();
  }
}

Module bind

In the Guice module bind the provider using eager singleton so that the Database is created eagerly at startup.

// bind the provider as eager singleton
bind(Database.class).toProvider(DatabaseProvider.class).asEagerSingleton()

Inject and ActiveRecord

As long as DatabaseConfig.setRegister(true) and DatabaseConfig.setDefaultServer(true) are used in the Guice provider then the Database instance created is also available via the DB singleton and that means both @Inject and the active record style can be used.

Edit Page