Technology moves fast! ⚡ Don't get left behind.🚶 Subscribe to our mailing list to keep up with latest and greatest in open source projects! 🏆


Subscribe to our mailing list

dropwizard-guice

Adds support for Guice to Dropwizard

Subscribe to updates I use dropwizard-guice


Statistics on dropwizard-guice

Number of watchers on Github 245
Number of open issues 27
Average time to close an issue about 2 months
Main language Java
Average time to merge a PR 22 days
Open pull requests 7+
Closed pull requests 12+
Last commit almost 2 years ago
Repo Created over 6 years ago
Repo Last Updated over 1 year ago
Size 212 KB
Organization / Authorhubspot
Latest Releasedropwizard-guice-1.0.0.3
Contributors12
Page Updated
Do you use dropwizard-guice? Leave a review!
View open issues (27)
View dropwizard-guice activity
View on github
Fresh, new opensource launches 🚀🚀🚀
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating dropwizard-guice for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

Dropwizard-Guice

A simple DropWizard extension for integrating Guice via a bundle. It optionally uses classpath scanning courtesy of the Reflections project to discover resources and more to install into the dropwizard environment upon service start.

Usage

    <dependencies>
        <dependency>
            <groupId>com.hubspot.dropwizard</groupId>
            <artifactId>dropwizard-guice</artifactId>
            <version>${current.version}</version>
        </dependency>
    </dependencies>

A list of available versions can be found at https://github.com/HubSpot/dropwizard-guice/releases

Simply install a new instance of the bundle during your service initialization

public class HelloWorldApplication extends Application<HelloWorldConfiguration> {

  private GuiceBundle<HelloWorldConfiguration> guiceBundle;

  public static void main(String[] args) throws Exception {
    new HelloWorldApplication().run(args);
  }

  @Override
  public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {

    guiceBundle = GuiceBundle.<HelloWorldConfiguration>newBuilder()
      .addModule(new HelloWorldModule())
      .setConfigClass(HelloWorldConfiguration.class)
      .build();

    bootstrap.addBundle(guiceBundle);
  }

  @Override
  public String getName() {
    return "hello-world";
  }

  @Override
  public void run(HelloWorldConfiguration helloWorldConfiguration, Environment environment) throws Exception {
    environment.jersey().register(HelloWorldResource.class);
    environment.lifecycle().manage(guiceBundle.getInjector().getInstance(TemplateHealthCheck.class));
  }
}

Auto Configuration

You can enable auto configuration via package scanning.

public class HelloWorldApplication extends Application<HelloWorldConfiguration> {

  public static void main(String[] args) throws Exception {
    new HelloWorldApplication().run(args);
  }

  @Override
  public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {

    GuiceBundle<HelloWorldConfiguration> guiceBundle = GuiceBundle.<HelloWorldConfiguration>newBuilder()
      .addModule(new HelloWorldModule())
      .enableAutoConfig(getClass().getPackage().getName())
      .setConfigClass(HelloWorldConfiguration.class)
      .build();

    bootstrap.addBundle(guiceBundle);
  }

  @Override
  public String getName() {
    return "hello-world";
  }

  @Override
  public void run(HelloWorldConfiguration helloWorldConfiguration, Environment environment) throws Exception {
    // now you don't need to add resources, tasks, healthchecks or providers
    // you must have your health checks inherit from InjectableHealthCheck in order for them to be injected
  }
}

Dropwizard Task requires a TaskName. Therefore when Auto Configuring a Task, you need to inject in the TaskName:

    @Singleton
    public class MyTask extends Task {

        @Inject
        protected MyTask(@Named("MyTaskName") String name) {
            super(name);
        }

        @Override
        public void execute(ImmutableMultimap<String, String> immutableMultimap, PrintWriter printWriter) throws Exception {

        }
    }

And bind the TaskName in your module:

bindConstant().annotatedWith(Names.named("MyTaskName")).to("my awesome task");

See the test cases: InjectedTask and TestModule for more details.

Environment and Configuration

If you are having trouble accessing your Configuration or Environment inside a Guice Module, you could try using a provider.

public class HelloWorldModule extends AbstractModule {

  @Override
  protected void configure() {
    // anything you'd like to configure
  }

  @Provides
  public SomePool providesSomethingThatNeedsConfiguration(HelloWorldConfiguration configuration) {
    return new SomePool(configuration.getPoolName());
  }

  @Provides
  public SomeManager providesSomenthingThatNeedsEnvironment(Environment env) {
    return new SomeManager(env.getSomethingFromHere()));
  }
}

Injector Factory

You can also replace the default Guice Injector by implementing your own InjectorFactory. For example if you want to use Governator, you can set the following InjectorFactory (using Java 8 Lambda) when initializing the GuiceBundle:

@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {

  GuiceBundle<HelloWorldConfiguration> guiceBundle = GuiceBundle.<HelloWorldConfiguration>newBuilder()
    .addModule(new HelloWorldModule())
    .enableAutoConfig(getClass().getPackage().getName())
    .setConfigClass(HelloWorldConfiguration.class)
    .setInjectorFactory((stage, modules) -> LifecycleInjector.builder()
        .inStage(stage)
        .withModules(modules)
        .build()
        .createInjector()))
    .build();

 bootstrap.addBundle(guiceBundle);
}

Testing

As of Dropwizard 0.8.x, when writing Integration Tests using DropwizardAppRule, you need to reset jersey2-guice by running:

JerseyGuiceUtils.reset();

Examples

Please fork an example project if you'd like to get going right away.

You may also find more updated and comprehensive examples in the test cases.

Enjoy!

dropwizard-guice open issues Ask a question     (View All Issues)
  • over 2 years AutoConfig not honouring Guice Singleton annotation on resource classes
  • over 2 years Compatiblity with Dropwizard 1.0?
  • almost 3 years @BeanParam + @QueryParam don't work with Dropwizard-guice
  • almost 3 years Integration Test using mocked beans
  • almost 3 years Binding annotations aren't being consistently honored
  • over 3 years System.exit() is evil, pls no
  • almost 4 years InjectedResourcesTest.java question
  • about 4 years [Question] bindListener declared in module not being fired
  • over 4 years Properly reset ServiceLocatorGenerator / RuntimeDelegate in a test environment
  • over 4 years AutoConfig not finding all resources in package
  • over 4 years Guice unable to create injector for Singletons depending on Configuration or Environment (Redux)
  • over 4 years banner.txt not picking up when using enableAutoConfig in GuiceBundle
  • almost 5 years Order of Managed objects added to environment
  • about 5 years Support Servlets with AutoConfig
  • over 5 years Dealing with an AuthProvider that takes an injected constructor parameter
  • over 6 years support filters
  • over 6 years Request: Testing Example
dropwizard-guice open pull requests (View All Pulls)
  • Initialize Guice after the environment has been set
  • Enable EagerSingletons using Managed and Guice Provider
  • Config
  • Injectable Modules, Named configuration data, and Injected Commands
  • #29 - servlet support
  • Injecting Jersey request-scoped services
  • [issue-98] Register GuiceServletContextListener
dropwizard-guice questions on Stackoverflow (View All Questions)
  • Dropwizard + Guice Bundle getting Application Configuration in the Module
dropwizard-guice list of languages used
Other projects in Java