Books I Like

Showing posts with label Guice. Show all posts
Showing posts with label Guice. Show all posts

Wednesday, October 21, 2009

Google Guice : Part 2 : Inject Config Value

Was Spring 3.0 just released ?

Right, Here is a link mentioning the same Spring3.0 release. I am really excited to check it out, specially the REST part of it. But yeah, let us save it for other posts.

I directly came here, where is the part One ?

If you haven't gone through the part 1 of this article, and are totally new to Google Guice, please check it out and set up your environment as described there.

What is the goal for this article ?

Since in the previous article we were able to set up a working project/program. Let us extend it further. Almost all of the applications needs to have some configuration properties, today we will learn to inject the property value from a config file.

Ummm.. before you dive into it, I just forgot what was the spring bean I used to configure it in a Spring App?

I guess you are probably talking about PropertyPlaceholderConfigurer.java. By the way, the other day I blogged about extending it.

Well...Lets code it :


public interface IPrinter {
public void print();
}

public class MyDummyPrinter implements IPrinter {
public void print() {
System.out.println("Article Printed !");
}
}

public interface IMailSender {
public void sendMail();
}

public class MyDummyMailSender implements IMailSender {
public void sendMail() {
System.out.println("Mail Sent !");
}
}

public interface ArticleService {
public void publishArticle();
}

import com.google.inject.Inject;
import com.google.inject.name.Named;
public class Article implements ArticleService {
private IMailSender mailSender;
private IPrinter printer;

private String advertizedAt;
private String articleHeading;

@Inject
Article(
@Named("advertised.at") String advertizedAt,
@Named("article.name") String articleHeading,
IMailSender mailSender, IPrinter printer) {
this.mailSender = mailSender;
this.printer = printer;
this.advertizedAt = advertizedAt;
this.articleHeading = articleHeading;
System.out.println("This article has been advertized at :" + advertizedAt +
" with the heading :" + articleHeading);
}

public void publishArticle() {
mailSender.sendMail();
printer.print();
}
}



Check out the Article.java code. We want to inject two properties namely "advertizedAt" and "articleHeading" throgh a config file. As you can see Guice comes with a built in annotation - named. So, as it appears, Guice should inject the value for these keys as defined in the config file.

Well, let us define our property file :


advertised.at=dZone
article.name=googleGuicePartTwo


But How will Guice know the property value unless it loads it. Does it has something like PropertyPlaceholderConfigurer ?

You are right, we are going to write some code to load the property file. As of now, I am not aware about any helper class who does it for us. If you know one please comment, or else I would update it once I know.


import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import java.util.Properties;
import java.net.URL;

public class MyArticleModule extends AbstractModule {
@Override
protected void configure() {
try {
Properties props = loadProperties();
Names.bindProperties(binder(),props);
} catch (Exception e) {
e.printStackTrace();
}
bind(IPrinter.class).to(MyDummyPrinter.class);
bind(IMailSender.class).to(MyDummyMailSender.class);
}

private static Properties loadProperties() throws Exception {
Properties properties = new Properties();
ClassLoader loader = MyArticleModule.class.getClassLoader();
URL url = loader.getResource("config.properties");
properties.load(url.openStream());
return properties;
}
}


So, before injection we are loading the config.properties. The code is straight forward. The piece important here to note is the use of com.google.inject.name.bindProperties which creates a constant binding to @Named(key) for each property.

Well , Let us see it in action :


import com.google.inject.Injector;
import com.google.inject.Guice;

public class MyBootStrapInvoker {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MyArticleModule());
Article article = injector.getInstance(Article.class);
article.publishArticle();
}
}


Sample Run :-


This article has been advertized at :dZone with the heading :googleGuicePartTwo
Mail Sent !
Article Printed !


Is this the best approach to do this way :

I am sure there must be a better way, as Guice always discourages bindings that uses a string, because the compiler can not check the string. So that means, if there is some spelling mistakes, we would see run time error (like we see in spring, if you make spelling mistakes). Let me know, if you know a better way.
Would appreciate your comments.

Sunday, October 18, 2009

Google Guice : Part 1

Over the weekend I was going through this video presented at Google IO 2009.
Please watch it if DI (a.k.a Dependency Injection) interests you.


Where is Guice being used in production :-
The video mentions Google uses it for Google Wave, Google Adwords, GMail, Orkut, Google Docs, Youtube...pretty much every new project .

This is how I talked with myself, in case it is gonna help you let us learn together.

Should I care to learn Guice, I already know/use Spring :-
Spring framework is much more than a DI framework.It made DI popular (although there were older DI framework available before it). Spring competes with JEE stack.
So, yeah we can say Spring is a super set of Google Guice. Guice wholly embraces annotations and generics, thereby enabling you to wire together and test objects with measurably less effort. Guice proves you can use annotations instead of error-prone, refactoring-adverse string identifiers.And of course it is much light weight.

Spring uses annotations too :- That is true. The newer versions (probably 2+) focuses more to use annotations. We may discuss the benefits of XML declarations vs annotations in a separate post, as it is a topic in itself .

There are so many annotations for different DI libraries, shouldn't it be standardized :- You are in luck. Check it out JSR330- http://code.google.com/p/atinject/

Well...so show me some code :-

I won't boar you with the definition(s) of DI, IOC (search it on google rather in case you are new to this). Goal of this post is to make you run a simple Guice Program.

Download the guice library, and add it in your classpath.

The interfaces and it's implementations are self explanatory :-



public interface IPrinter {
public void print();
}

public class MyDummyPrinter implements IPrinter {
public void print() {
System.out.println("Article Printed !");
}
}

public interface IMailSender {
public void sendMail();
}

public class MyDummyMailSender implements IMailSender {
public void sendMail() {
System.out.println("Mail Sent !");
}
}

public interface ArticleService {
public void publishArticle();
}

import com.google.inject.Inject;
public class Article implements ArticleService{
private IMailSender mailSender;
private IPrinter printer;

@Inject
Article (IMailSender mailSender, IPrinter printer) {
this.mailSender = mailSender;
this.printer = printer;
}
public void publishArticle() {
mailSender.sendMail();
printer.print();
}
}


As shown in the above program, we want the mailSender and printer to be injected.
So, note the @inject annotation over the Article Constructor.

Lets inject the dependencies. Well, if you have worked with Spring's XML declarations for defining and injecting the dependencies, then think the next java code to be it's counter part in Guice.


import com.google.inject.AbstractModule;
public class MyArticleModule extends AbstractModule {
protected void configure() {
bind(IPrinter.class).to(MyDummyPrinter.class);
bind(IMailSender.class).to(MyDummyMailSender.class);
}
}


What I like here is the readability (It is like I am coding in Ruby :)). The code clearly shows that IPrinter.class is bound to MyDummyPrinter.class. Similarly, with the other line.

Cool..Now let us launch/bootstrap the Guice. For the Spring folks, think it similar to the code you write to load spring config beans (remember : ApplicationContext ctx = new ClasspathApplicationContext("example.xml")).


import com.google.inject.Injector;
import com.google.inject.Guice;

public class MyBootStrapInvoker {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MyArticleModule());
Article article = injector.getInstance(Article.class);
article.publishArticle();
}
}


And that's it. You are running Guice !!!

Hopefully, we will dive more in depth in the second post on the same topic.
Please let me know your comments, so the next time I could offer more.

Get at Amazon