Playing with Google Guice

It’s been a long time coming but I’ve finally started dabbling in dependency injection for my swing frameworks. It’s taken me a quite a while to get a feel for where and how it can/should be used. Given the complexity of even an average Swing application I’d been loathed to convert all my UI construction and wiring over to a container, but I’d also love to create a framework environment where I can install all my standard behaviours in one line.

I’d also been wanting to consolidate my various frameworks and utilities into a single application framework (along the lines of JSR-296) but wanted to try out the dependency injection route.

Anyway, so far I’ve been very pleased with the results. I’ve been able to create services for controlling the splash screen, determining the runtime environment and providing runtime environment services, configuring Look and Feel settings and so on. With Guice you can easily create default implementations of your services so you can have the basics going with zero configuration.

So the following useless example shows what’s necessary to get a frame up and create a file in the default application data directory.

public class MyApplication
extends SingleFrameApplication
{
   public MyApplication()
   {
      super("MyApplication", MyApplicationFrame.class);
   }

   public void initialise(String[] args)
   {
      // The EnvironemntService ensures it's the correct location
      // based on the runtime platform.. i.e. `C:\AppData\MyApplication`
      // on windows and `~/Library/Application Support/MyApplication` 
      // on the Mac.

      // AbstractApplication provides getters for standard services so
      // you don't have to magically discern their existence.
      EnvironmentService env = getEnvironmentServices();
      File logFile = env.getFileInAppDataDirectory("logs/my-app.log");

      // do stuff with the file...
      ....
   }
}

Then the application can be simply started using the following.

public static void main(String[] args)
{
   Launcher.launch(MyApplication.class, args);
}
This entry was posted in Development, UIs and Swing. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *