java的guice3.0依赖注入方法,这里采用的是官方文档的第一种注入方法。
jar包下载地址:
https://github.com/google/guice/releases/download/3.0/guice-3.0.zip
工程目录结构:
接口及相应的代码模块
/** * */ package com.test.func; /** * @filename speaking.java * @author code by jianghuiwen * @mail [email protected] * * 上午11:30:14 */ public interface speaking { public void saying(); }
/** * */ package com.test.func.impl; import com.test.func.speaking; /** * @filename JackSpeaking.java * @author code by jianghuiwen * @mail [email protected] * * 上午11:30:48 */ public class JackSpeaking implements speaking{ /* (non-Javadoc) * @see com.test.func.speaking#saying() */ @Override public void saying() { // TODO Auto-generated method stub System.out.println("saying something......."); } }
/** * */ package com.test.guice; import com.google.inject.AbstractModule; import com.test.func.speaking; import com.test.func.impl.JackSpeaking; /** * @filename Model.java * @author code by jianghuiwen * @mail [email protected] * * 上午11:32:54 */ public class Model extends AbstractModule{ /* (non-Javadoc) * @see com.google.inject.AbstractModule#configure() */ @Override protected void configure() { // TODO Auto-generated method stub bind(speaking.class).to(JackSpeaking.class); } }
/** * */ package com.test.guice; import com.google.inject.Guice; import com.google.inject.Injector; import com.test.func.speaking; /** * @filename Main.java * @author code by jianghuiwen * @mail [email protected] * * 上午11:23:29 */ public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Injector injector = Guice.createInjector(new Model()); speaking speakingperson = injector.getInstance(speaking.class); speakingperson.saying(); } }
总结:
用了配置话的注入模式,不用再new一个对象,麻烦的地方就是一定要手工的配置public class Model extends AbstractModule这样一个类。