实例绑定(Instance Bindings)


Instance Bindings

在Guice中你可以将一个具体的实例绑定到一个类型上。通常这种用法只用在自身没有任何依赖的对象上,例如值对象(value objects):

bind(String.class)
    .annotatedWith(Names.named("JDBC URL"))
    .toInstance("jdbc:mysql://localhost/pizza");
bind(Integer.class)
    .annotatedWith(Names.named("login timeout seconds"))
    .toInstance(10);

需要注意的是,不要在非常复杂的对象上使用.toInstance()绑定,因为这可能会影响应用启动的速度。此时,你可以使用@Provides方法

results matching ""

    No results matching ""