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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值