Saturday, April 2, 2011

A simple AppEngine Guice Module (Part 1)

This post is about a simple Guice AppEngine module I've written, which I find very useful, hence, I decided to share it.

The code is available here

The module will get your AppEngine project started quickly, here is a typical bootstrap (GuiceServletContextListener) code for a simple app:
package com.codeark.appengine;

import com.codeark.appengine.objectify.ObjectifyModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.servlet.GuiceServletContextListener;

public class Bootstrap extends GuiceServletContextListener {

 @Override
 protected Injector getInjector() {

  Module aeModule = 
   AppEngineModule.build().withDatastoreService()
    .withUrlFetchService().withMemcacheService().withMailService();

  Module myModule = new MyOtherModule();
  
  return Guice.createInjector(aeModule, myModule);
 }
}
The module's Fluent Interface API(which I like so much) exposes a single static build() method which returns an instance of the module. You can then configure which services AppEngine should initialize using the .With*Service() methods.

later you can do:
class Classy {
 @Inject
 public Classy(MemcacheService service, MailService mail) {
 ...
 }
}
There are several other goodies included in the source, which I will discuss in later posts: A simple abstraction over UrlFetchService and an Objectify module.

No comments:

Post a Comment