Guice系列之用户指南(七)

原文地址:https://code.google.com/p/google-guice/wiki/ToConstructorBindings

Constructor Bindings(构造器绑定):在父类型上绑定子类实现的构造函数。

贴代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public interface Animal {
    void say();
}
 
import com.google.inject.AbstractModule;
 
public class AnimalModule extends AbstractModule {
 
    @Override
    protected void configure() {
        bind(String.class).toInstance("Tom");
         
        try {
            bind(Animal.class).toConstructor(Cat.class.getConstructor(String.class));
        } catch (NoSuchMethodException e) {
            addError(e);
        }
         
        System.out.println("run AnimalModule.configure()");
    }
}
 
public class Cat implements Animal {
     
    String name;
     
    public Cat(String name) {
        this.name = name;
        System.out.println("run Cat.constructor()");
    }
     
    @Override
    public void say() {
        System.out.println("i am a cat");
    }
     
    @Override
    public String toString() {
        return "name==>" + this.name;
    }
}
 
import com.google.inject.Guice;
import com.google.inject.Injector;
 
public class Test {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new AnimalModule());
        Animal cat = injector.getInstance(Animal.class);
        System.out.println(cat);
        cat.say();
    }
}

执行结果:
run AnimalModule.configure()
run Cat.constructor()
name==>Tom
i am a cat

练习代码在这里

此条目发表在编程语言分类目录,贴了, 标签。将固定链接加入收藏夹。