import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.util.*; import javax.inject.Qualifier; import javax.inject.Singleton; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provides; import com.google.inject.name.Names; import com.google.inject.name.Named; import com.google.inject.AbstractModule; @Qualifier @Retention(RUNTIME) @interface VoidParam {} @Qualifier @Retention(RUNTIME) @interface OneParam {} class Processer { protected String url; public void hello3() { System.out.println("hello2"); } public void setUrl(String url) { this.url = url; } } class SubProcesser extends Processer { @Override public void hello3() { System.out.println("hello29"); } } class BillingModule extends AbstractModule{ @Override protected void configure() { //bind(Processer.class).to(SubProcesser.class); bind(String.class).annotatedWith(Names.named("URL")).toInstance("http://localhost"); } @Provides @VoidParam static Processer provideProcesser1() { Processer proc = new SubProcesser(); System.out.println("provideProcesser1 no url"); return proc; } @Provides @OneParam static Processer provideProcesser2(@Named("URL") String url) { Processer proc = new SubProcesser(); proc.setUrl(url); System.out.println("provideProcesser2 url:" + url); return proc; } } @Singleton public class test3 { private Processer process; @Inject public test3(@VoidParam Processer p, @Named("URL") String url) {//也可調用@OneParam Processer p this.process = p; System.out.println("test3 url:" + url); } public void hello() { System.out.println("hello"); this.process.hello3(); } public static void main(String[] args) { Injector injector = Guice.createInjector(new BillingModule()); test3 t = injector.getInstance(test3.class); t.hello(); } }