Google Guice是一个轻量级Dependency Injection依赖注入框架,能够提供动态注入,即当不知道注射的这个对象注射给谁呢,需要在运行时才能得到的的这个接口的实现,这是Spring DI所不具有的,Spring DI所有配置都是写死的,并且Spring DI在应用程序启动时所有依赖注入关系都会初始好,而Google Guice则可以根据需要进行依赖注入初始化,也就是说只有当需要时,就可以对依赖注入关系进行初始化。
引入Google Guice包,从这个网址可以下载http://google-guice.googlecode.com/files/guice-3.0.zip
一。CommentDao.java
package com.template.guice; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 11-8-2 * Time: 下午9:37 */ public interface CommentDao { public void comment(String message); }
二。CommentDaoImpl.java
package com.template.guice; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 11-8-2 * Time: 下午9:38 */ public class CommentDaoImpl implements CommentDao { public CommentDaoImpl() { } @Override public void comment(String message) { System.out.print(message); } }
三。CommentService.java
package com.template.guice; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 11-8-2 * Time: 下午9:39 */ public interface CommentService { public void comment(); }
四。CommentServiceImpl.java
package com.template.guice; import com.google.inject.Inject; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 11-8-2 * Time: 下午9:39 */ public class CommentServiceImpl implements CommentService { private CommentDao commentDao; @Inject public CommentServiceImpl(CommentDao commentDao) { this.commentDao = commentDao; } @Override public void comment() { commentDao.comment("This is a comment message!"); } public void setCommentDao(CommentDao commentDao) { this.commentDao = commentDao; } }
五。CommentModule.java
package com.template.guice; import com.google.inject.AbstractModule; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 11-8-2 * Time: 下午9:46 */ public class CommentModule extends AbstractModule { @Override protected void configure() { bind(CommentDao.class).to(CommentDaoImpl.class); } }
六。Main.java
package com.template.guice; import com.google.inject.Guice; import com.google.inject.Injector; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 11-8-2 * Time: 下午9:55 */ public class Main { public static void main(String[] args) { Injector injector = Guice.createInjector(new CommentModule()); CommentService commentService = injector.getInstance(CommentServiceImpl.class); commentService.comment(); } }
@Inject表示Guice会隐式调用CommentServiceImpl的构造方法,而CommentModule则表示需要将CommentDao以CommentDaoImpl来注入对象中。