Guice Hello World

March 12, 2007

A new project called Guice (pronounced Juice, but starts with a G instead of J because it's Googlerrific) has been created. Guice aims to be a better Dependency Injection (DI) framework for Java. The de facto DI framework for Java is currently Spring. Spring provides a lot of things besides DI, but I think DI is it's main selling point. I often use Spring in projects only for it's DI. I use Stripes as my Web MVC framework and Hibernate as my ORM framework, so I don't need Spring's MVC layer or JDBC Template. I do use Spring's declarative transaction management and hibernate configuration features, but that's only because once you start using Spring for DI, it's easy to use those features as well, but they could be easily replaced.

The main disadvantage of Spring, in my opinion, is the amount of XML files that you have to create to configuration you application. The thing I dislike most about the XML configuration is that it is not type safe, and just like Bob Lee says:

I'm using a strongly typed language; why would I want to throw all of this perfectly good type information away? If I wanted that, I'd use Ruby.

I don't think he meant that statement as a knock against Ruby, he's just saying that if you are programming in Java, then you want to use type safety as much as possible. Annotations and Generics, features added to Java in Java 5, can allow you to do that, and Guice aims to provide dependency injection via Annotations rather than XML.

So I decided to take a look at Guice, and although the documentation is pretty good, it doesn't have a working "Hello World" type example to get you going, so I figured I would provide one here. I encourage you to play along at home.

First, download Guice, setup a new project in your favorite IDE, and add guice-1.0.jar to your classpath. What we're going to do is create a basic domain model object, Foo, and a DAO-like Manager for Foo, and then create a controller that depends on the FooManager, and has that dependency set using Guice. So here we go. Create the Foo class:

public class Foo {

    private Long id;
    private String name;

    //Generate and getters/setters in your IDE

}

Then create the interface for the FooManager:

public interface FooManager {

    public Foo get(Long id);
    public void save(Foo foo);

}    

Then create an implementation of the FooManager. In real life, you might implement this with an ORM framework like Hibernate, but this simple little thing serves the purpose for this example:

public class FooManagerImpl implements FooManager {

    private static Long fooSequence = 1l;
    private static final Map<Long, Foo> foos = new HashMap<Long, Foo>();

    public Foo get(Long id) {
        return foos.get(id);
    }

    public void save(Foo foo) {
        if(foo == null) return;
        if(foo.getId() == null) {
            foo.setId(fooSequence);
            fooSequence++;
        }
        foos.put(foo.getId(), foo);
    }
}

And for the last part of our app, we'll create a controller that calls our manager. This controller is sort of like what a controller in a web app might be like:

public class FooController {

    private FooManager fooManager;

    //----- Controller Actions -------------------------------------------------
    public Foo create(String name) {
        Foo foo = new Foo();
        foo.setName(name);
        fooManager.save(foo);
        return foo;
    }

    public Foo retrieve(Long id) {
        return fooManager.get(id);
    }

    //----- Getters/Setters ----------------------------------------------------
    public FooManager getFooManager() {
        return fooManager;
    }

    @Inject
    public void setFooManager(FooManager fooManager) {
        this.fooManager = fooManager;
    }

}

You can see that with the annotation Inject on the fooManager setter, we are asking Guice to inject a fooManager instance into our controller. Continuing with the web app like architecture of our app, we'll create a dispatcher. In a real app, this would be the FrontController responsible for directing the request to be handled by the appropriate controller action, but for our simple app, we'll just hard code 2 controller action methods to be called:

public class FooDispatcher {

    public static void main(String[] args) {

        FooController controller = new FooController();
        Injector injector = Guice.createInjector(new FooModule());
        injector.injectMembers(controller);

        //Our action is now injected with a FooManager, so let's use it
        Foo foo = controller.create("Bar");
        Foo bar = controller.retrieve(foo.getId());
        System.out.println("bar.name => "+bar.getName());

    }

}

As you can see here, we've now got some Guice specific code. First we create an injector using the FooModule. The FooModule is a class we create that serves as the configuration for Guice, we'll get to that in a minute. The creation of this injector is something that you would do once, probably upon application startup. Then, we ask the injector to inject our controller instance with its dependencies. The simple Inject annotation we added on the setFooManager method of our controller is all the info the injector needs to set up our controller. Next you see we call 2 action methods, one to create a new Foo instance, and then another to retrieve it.

So let's look at the FooModule, which is where we do our Guice configuration:

public class FooModule extends AbstractModule {

    protected void configure() {
        bind(FooManager.class)
            .to(FooManagerImpl.class)
            .in(Scopes.SINGLETON);
    }

}

What this says is that when something needs a FooManager injected into it, use a singleton instance of FooManagerImpl to fulfill that dependency. We can actually use annotations to further simplify this configuration. First, we add the ImplementedBy annotation to the FooManager interface:

@ImplementedBy(FooManagerImpl.class)
public interface FooManager {

    public Foo get(Long id);
    public void save(Foo foo);

}

This basically says to Guice that we want FooManagerImpl to be the default implementation class for FooManager. Also, we can specify that by default we want FooManagerImpl to be a singleton:

@Singleton
public class FooManagerImpl implements FooManager {

    private static Long fooSequence = 1l;
    private static final Map<Long, Foo> foos = new HashMap<Long, Foo>();

    public Foo get(Long id) {
        return foos.get(id);
    }

    public void save(Foo foo) {
        if(foo == null) return;
        if(foo.getId() == null) {
            foo.setId(fooSequence);
            fooSequence++;
        }
        foos.put(foo.getId(), foo);
    }
}

Now, we can modify our module to look like this:

public class FooModule extends AbstractModule {

    protected void configure() {
        bind(FooManager.class);
    }

}

An now when we re-run our FooDispatcher, every thing still works. In real life, there would be some core mechanism in the web app framework to handle creating the injector and injecting dependencies into the controller instances, and I'm sure it would be fairly trivial to implement that into Stripes.

Although some people don't think Guice is going to replace Spring, I think for projects where Spring is being used mostly for DI, we will see Guice or something like it start to replace Spring. I also predict that in response to this, Spring will be forced into incorporating an annotation-based configuration mechanism into its core codebase in order to remain popular in the oncoming wave of Annotation based "zero" configuration frameworks like Stripes, Struts 2 and Hibernate.

UPDATE: Monday, March 12, 5:18pm

Thanks to a tip from Bob, I've discovered that once you have every thing configured by annotations, as we do at the end of this example, you can completely remove the FooModule, which gives you the code like this in the dispatcher:

public class FooDispatcher {

    public static void main(String[] args) {

        FooController controller = new FooController();
        Injector injector = Guice.createInjector();
        injector.injectMembers(controller);

        //Our action is now injected with a FooManager, so let's use it
        Foo foo = controller.create("Bar");
        Foo bar = controller.retrieve(foo.getId());
        System.out.println("bar.name => "+bar.getName());

    }

}

The point is that for any class that you can configure with annotations, you don't need to explicitly define them in a module, or anywhere. So take an app with 50 different manager classes, all you would have to do is create a manager interface, annotate it as a singleton, and then create the default implementation. Compare that with a minimum of 50 bean entries in a Spring context configuration XML file, and you can see how Guice can really start to simplify your configuration.

Posted in Technology | Tags Spring, Hibernate, Stripes, Java, DependencyInjection, Guice | 28 Comments

The Power of Dynamic Methods

February 14, 2007

Today I was writing some Java code and needed to make methods like this:

@Transient
public String getThingsAsString() {
    if(things != null) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for(Thing t: things) {
            if(!first) {
                sb.append(", ");
            } else {
                first = false;
            }
            sb.append(t.getName());
        }
        return sb.toString();
    }
    return null;
}

Basically, I have an object that has a Collection of Things objects, and I need to print the name of each Thing in a comma-separated list. I have several different Collections and so I need to repeat this for each one. I could "simplify" this by creating an interface that all of my different objects like Thing implement, for example calling it NamedEntity. This means that each one of these objects are guaranteed to have a getName() method. After creating that interface and modifying all the object so that they implement it, I would write a utility method to print a NamedEntity as a String. So then each above method would look like:

public String getThingAsString() {
    return NamedEntityUtil.getNamedEntitiesAsString(things);
}

But this still means that I have to create a getXXXAsStringMethod for each collection. I could just call the utility method when I need the string, but the problem is that I need this string within JSP pages, and you can't call the static methods from a JSP without resorting to scriplets. This is especially a pain because it is difficult to mix JSTL and scriptlets.

So what could you do if you need to do this in Rails? Well for starters, you can use one line of Ruby code to do it:

things.collect {|t| t.name}.join(", ")

You could also create one view helper to make the syntax a little cleaner, and then re-use it. Ths view helper method would be:

def join_names(things, sep=", ")
  things.collect {|t| t.name}.join(sep)
end

And look at that, we easily can now optionally pass a different separator. But that's not the point I want to illustrate in this post. Let's say for some reason in Rails we really needed to create various method to print the various collections as strings. Well that would be easy too. We would just put this inside of our class that has a Collection of things:

["things", "other_things"].each do |name|
  define_method("#{name}_as_string") do self.join_names(self.send(name)) end
end

What this ruby magic does is dynamically create methods for each collection. It allows you call methods like this:

whatever.things_as_string
whatever.other_things_as_string

Like I said, you probably wouldn't really do this for this example, but the point here is that with Ruby, you can write code that writes code, and that can be very powerful.

I first heard of this concept in the book Hackers and Painters by Paul Graham. This is the best book on programming I have ever read, and if you haven't read it, go out and buy it and read it. It actually isn't very technical. It doesn't teach you any specific programming techniques, but it's just a great book. My favorite chapter is Why Nerds Are Unpopular.

In a chapter called Beating the Averages, for which the full text is available on Paul Graham's website, like many of the chapters of the book, he talks about how Lisp macros are programs that write programs, and at the time, it sounded like a great idea, but I just didn't get it. He said:

Programs that write programs? When would you ever want to do that? Not very often, if you think in Cobol. All the time, if you think in Lisp.

Code that writes code? When would you ever want to do that? Not very often, if you think in Java. All the time, if you think in Ruby.

Posted in Technology | Tags Hibernate, Ruby, Java, Rails | 0 Comments

Learning from Rails

February 14, 2007

I've said before that learning different programming frameworks and languages makes you a better programmer. For example, learning about Ruby on Rails will make you a better Java programmer even if you don't ever build any apps in Ruby on Rails. Here's an example of that.

In a recent post, I pointed out how Rails make querying across relationships easy with the use of :includes. This adds outer joins to the SQL query. In Hibernate, this is referred to as eager fetching.

In Hibernate 3, by default, any associated collections of an object are loaded lazily. What this means is that by default, you just get a proxy to a collection that contains no data. Upon first access of the collection, hibernate goes and gets the data from the database when you need it. Rails also work like this.

In some cases, this is a good thing, because you are fetching only the data you need from the database, which leads to better performance. There are 2 cases where this becomes a problem:

First, you don't make your first call to the collection until after the Hibernate Session is closed. This will cause the dreaded LazyInitializationException. There are two ways to handle this problem:

a. You can open a session at the very beginning of request and then close it at the very end. This is most often done with a Filter, commonly known as the OpenSessionInView pattern. Incidentally, Rails doesn't require this, it "Just Works".

b. You can eagerly load all the data that you want.

The second problem caused when using lazy loading is the dreaded N+1 Select problem. Let's say you select all the posts from your blog, and each post has a collection of comments associated to it. So now that you have all your posts, you want to print out each post and each comment for each post. You'll basically end up doing some kind of nested for loop, but each time you do a loop on the comments of a post, your lazy loaded comments collection will have to get loaded from the database in a separate query. So the SQL queries executed during your request will be:

SELECT * FROM posts
SELECT * FROM comments WHERE post_id = 1
SELECT * FROM comments WHERE post_id = 2
SELECT * FROM comments WHERE post_id = 3
...

This is where the N+1 name comes from. You execute 1 query for the main object (posts, in this case), and then N queries, where N is the number of main objects. Now imagine if each comments had a collection of some kind associated to it. Then this becomes (N*M)+1, and this starts to become a real strain on your database, not to mention making your pages slow.

So, in either case 1b or 2, you want to use SQL joins to get all the data at once. When doing this in Java, you usually have a Data Access Object (DAO), that is where your Hibernate code is. So PostDAO.get(Long id) gets the post with the given id, but all collections are loaded lazily. To have them loaded eagerly, you create another method like PostDAO.getWithComments(Long id), which, if you are using Hibernate's Criteria API, you will end up having a line of code like setFetchMode("comments", FetchMode.JOIN). This is roughly equivalent to Rails' :include option in the find method.

The difference is that the Rails find method is so simple and expressive, you could feel confident using the :include in the controller layer. In Java, to accomplish the same thing, you need to set the fetch mode on the criteria, which means you would need to have access to the Hibernate Criteria object outside of the DAO. This would be considering exposing the details of the persistence layer to the business layer, and therefore a bad design.

So that's why you create those findWithComments methods. But the problem is that some times you have an object with several associations and there are various cases where you need certain associations and not others. Now you will have to have a lot of methods on your DAO like findWithCommentsAndSomethingAndSomethingElse. So when I was thinking about this the though occurred to me wouldn't it be great if there was something like includes in Java/Hibernate?

Well, you can easily mimic something similar. If you write a DAO method like PostDAO.find(Collection<String> includes), you can pass a collection of the names of the associations you want, and then inside the DAO method do something like this:

DetachedCriteria c = DetachedCriteria.forClass(Post.class)
for(String include: includes) {
    c.setFetchMode(include, FetchMode.JOIN);
}

You will get back an object will all of the associations that you need loaded. This isn't rocket science, but I'm just not sure that I would have thought about doing this had I not seen the way it is implemented in Rails.

Posted in Technology | Tags Hibernate, Ruby, Java, Rails | 16 Comments

PaulBarry.com 3.0

January 28, 2007

So I've finally finished the latest version of my site. The first version of my site went online on March 3rd of 2006 using WordPress. Then on my last birthday, I switched to Typo. Now, I've got up the first version of my site that I have built myself, using Java, Stripes, Spring and Hibernate. I'm using Resin as the Web/Application server and MySQL for the database. The OS is Ubuntu and it is hosted with VPSLand.

I hoping that this version will be more stable than the previous version. If you are having any problems using the site, let me know.

Posted in Technology | Tags Resin, Spring, Hibernate, Stripes, MySQL, Java, Ubuntu | 6 Comments

Hibernate vs. iBatis

January 14, 2007

I was googling for something on the internet and cam across this post I made to the iBatis mailing list almost 2 years ago. I think for the most part this still holds true, although when I made this statement I was referring to Hibernate 2. Hibernate 3 has some features that make Hibernate even more usable for odd database structures, such as [the ability to map SQL queries to objects][2]. The criteria API is much improved in Hibernate 3, and Hibernate Annotations make configuration of Hibernate much easier. I think these feature make the argument for using Hibernate even stronger, but iBatis is still a great framework to use for certain scenarios.

[2]: http://www.hibernate.org/hib_docs/v3/reference/en/html/querysql.html#querysql-load

Posted in Technology | Tags iBatis, Hibernate, Java | 0 Comments

  Older Articles >>