原文地址:https://code.google.com/p/google-guice/wiki/JustInTimeBindings
JustInTimeBindings(即时绑定):主要是在@ImplementedBy和@ProvidedBy实现。
贴代码:
import com.google.inject.ImplementedBy; @ImplementedBy(Cat.class) public interface Animal { void say(); } public class Cat implements Animal { @Override public void say() { System.out.println("i am a cat"); } } import com.google.inject.ProvidedBy; @ProvidedBy(HumenProvider.class) public interface Humen { void say(); } import com.google.inject.Provider; public class HumenProvider implements Provider<Humen> { @Override public Humen get() { Humen humen = new Student(); System.out.println("Provider.get()"); return humen; } } public class Student implements Humen { @Override public void say() { System.out.println("i am a student"); } } import com.google.inject.Guice; import com.google.inject.Injector; public class Test { public static void main(String[] args) { Injector injector = Guice.createInjector(); Animal animal = injector.getInstance(Animal.class); System.out.println(animal.getClass().getSimpleName()); animal.say(); Humen humen = injector.getInstance(Humen.class); System.out.println(humen.getClass().getSimpleName()); humen.say(); } }
执行结果:
Cat
i am a cat
Provider.get()
Student
i am a student