Guice注解实现一个类型绑定多个实现.

来源:互联网 发布:流程 数据库设计 编辑:程序博客网 时间:2024/06/17 12:48
package com.ilucky.guice.test5;import com.google.inject.Guice;import com.google.inject.Injector;import com.google.inject.Key;/** * v1.0:20161116 * 注解实现一个类型绑定多个实现. * 在Java的语言中,一个接口可以有多个实现类,基于这个思想,Guice提供了注解的方式,实现一个类型绑定多个实现. */public class MainTest {    public static void main(String[] args) {        Injector injector = Guice.createInjector(new PersonModule());        Person teacher = (Person)injector.getInstance(Key.get(Person.class, TeacherAnno.class));        teacher.say("teacher......");        Student student = (Student)injector.getInstance(Key.get(Person.class, StudentAnno.class));        student.say("student......");    }}/**Teacher=teacher......Student=student......*/
package com.ilucky.guice.test5;import com.google.inject.Binder;import com.google.inject.Module;public class PersonModule implements Module {    public void configure(Binder binder) {        binder.bind(Person.class).annotatedWith(TeacherAnno.class).to(Teacher.class);        binder.bind(Person.class).annotatedWith(StudentAnno.class).to(Student.class);    }}
package com.ilucky.guice.test5;public interface Person {    public void say(String say);}
package com.ilucky.guice.test5;public class Student implements Person  {    public void say(String say) {        System.out.println("Student="+say);    }}
package com.ilucky.guice.test5;public class Teacher implements Person {    public void say(String say) {        System.out.println("Teacher="+say);    }}
package com.ilucky.guice.test5;import static java.lang.annotation.RetentionPolicy.RUNTIME;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.Target;import com.google.inject.BindingAnnotation;@Target({ ElementType.TYPE, ElementType.METHOD })@Retention(RUNTIME)@BindingAnnotationpublic @interface StudentAnno {}
package com.ilucky.guice.test5;import static java.lang.annotation.RetentionPolicy.RUNTIME;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.Target;import com.google.inject.BindingAnnotation;@Target({ ElementType.TYPE, ElementType.METHOD })@Retention(RUNTIME)@BindingAnnotationpublic @interface TeacherAnno {}
阅读全文
0 0