Introduce Guice with Example
3658 ワード
The motivation of Guice Guice alleviates the need for factories and the user of new operator in Java Make youself confident with Java's type safe nature. Helps you design better API Easy tests Less boilerplate code Works on Java SE, Java EE, Android and GWT
Let me give you a little taste of Guice by an example.
For complete reference and documents, visit Guice project home .
Let me give you a little taste of Guice by an example.
public interface Shorter {
String shortenUrl(String text);
}
public class UrlShortener implements Shorter {
public String shortenUrl(String text) {
// Local or remote URL shorted service request here
return "short-url";
}
}
public interface WeiboSender {
void send(String text);
}
public class WeiboBrowserSender implements WeiboSender {
@Override
public void send(String text) {
// Send weibo.
System.out.println("Weibo was sent out: " + text);
}
}
import com.google.inject.Inject;
/**
* Weibo client for posting, first it will try to shorten url, then send the weibo out.
* <p/>
* User: George Sun
* Date: 7/12/13
* Time: 7:25 PM
*/
public class WeiboClient {
private WeiboSender sender;
private UrlShortener urlShortener;
// Note the Inject here, this is the key of this example.
@Inject
public WeiboClient(WeiboSender sender, UrlShortener urlShortener) {
this.sender = sender;
this.urlShortener = urlShortener;
}
public void postWeibo(String text) {
String weiboText = getWeiboText();
if (weiboText.length() > 140) {
weiboText = urlShortener.shortenUrl(weiboText);
}
if (weiboText.length() <= 140) {
sender.send(weiboText);
}
}
private String getWeiboText() {
return "Sample Weibo text here.";
}
}
import com.google.inject.AbstractModule;
/**
* Tell Guice what to inject, then Guice will inject instances when needed.
* <p/>
* User: George Sun
* Date: 7/12/13
* Time: 7:40 PM
*/
public class WeiboModule extends AbstractModule {
@Override
protected void configure() {
bind(WeiboSender.class).to(WeiboBrowserSender.class);
bind(Shorter.class).to(UrlShortener.class);
}
}
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Driver class.
* <p/>
* User: George Sun
* Date: 7/12/13
* Time: 7:44 PM
*/
public class Main {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new WeiboModule());
WeiboClient weiboClient = injector.getInstance(WeiboClient.class);
String sample = "Sample weibo text here.";
weiboClient.postWeibo(sample);
}
}
For complete reference and documents, visit Guice project home .