Skip to content

Instantly share code, notes, and snippets.

@zedar
Last active November 29, 2018 01:05
Show Gist options
  • Save zedar/56ef8c195780c816d22f to your computer and use it in GitHub Desktop.
Save zedar/56ef8c195780c816d22f to your computer and use it in GitHub Desktop.
Ratpack: bind object instance to Guice registry

Binding object instances as singletons

To bind object instance to be accessible accross handlers and custom classes define module and provider method. Add @Singleton annotation to have one instance for all injections.

import com.google.inject.AbstractModule
import com.google.inject.Scopes
import com.google.inject.Provides
import com.google.inject.Singleton

class CallerModule extends AbstractModule {
  protected void configure() {
    bind(CallerService.class).in(Scopes.SINGLETON)
  }
  
  @Provides @Singleton
  void provideCtx() {
    return new CallerCtx()
  }
}

Then in handler you have access to this CallerCtx class instance.

ratpack {
  bindings {
    add new CallerModule()
  }
  
  handlers {
    handler { CallerCtx cCtx, PublicAddress publicAddress ->
      if (cCtx && !cCtx.serverUrl) {
        cCtx.serverUrl = publicAddress.getAddress(context).toString()
      }
    }
    
    post("call") { CallerCtx cCtx ->
      
    }
  }
}

The same instance of CallerCtx class is accessible from inside custom class:

import javax.inject.Inject

class CallerService {
  @Inject CallerCtx cCtx
}
@benwilkes9
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment