Provider

Create a Guice Provider that programmatically creates an Ebean database instance.

Example 1

Example provider implementation using DatabaseConfig and DatabaseFactory.

import io.ebean.Ebean;
import io.ebean.EbeanServer;
import com.google.inject.Provider;

public class EbeanServerProvider implements Provider<EbeanServer> {

  @Override
  public EbeanServer get() {

    ServerConfig config = new ServerConfig();
    config.setName("pg");
    // load configuration from ebean.properties
    config.loadFromProperties();
    config.setDefaultServer(true);
    ...
    // other programmatic configuration

    return EbeanServerFactory.create(config);
  }
}

Example 2

Example provider implementation using Ebean that implicitly creates the default EbeanServer using ebean.properties.

import io.ebean.Ebean;
import io.ebean.EbeanServer;
import com.google.inject.Provider;

public class EbeanServerProvider implements Provider<EbeanServer> {

  @Override
  public EbeanServer get() {

    // EbeanServer configured by ebean.properties
    return Ebean.getDefaultServer();
  }
}

Module bind

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

// bind the provider as eager singleton
bind(EbeanServer.class).toProvider(EbeanServerProvider.class).asEagerSingleton()

Inject and ActiveRecord

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