第三章 【第三节】 实例绑定(InstanceBindings):Guice指导教程(原创翻译)

目录
[隐藏]

实例绑定 Instance Bindings

将一个类型绑定到一个特定的实例对象。通常用于一个本身不依赖其它类的类型,如各种基本类型。

You can bind a type to a specific instance of that type. This is usually only useful only for objects that don’t have dependencies of their own, such as 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注解方法来替代它。

Avoid using .toInstance with objects that are complicated to create, since it can slow down application startup. You can use an @Provides method instead.


实例

InstanceBindings(实例绑定):基本类型直接绑定值。

import com.google.inject.Inject;
import com.google.inject.name.Named;
 
public class Configure {
     
    String jdbcUrl;
    int loginTimeout;
     
    @Inject
    public Configure(@Named("JDBC URL") String jdbcUrl, 
            @Named("login timeout seconds") int loginTimeout) {
        this.jdbcUrl = jdbcUrl;
        this.loginTimeout = loginTimeout;
    }
     
    @Override
    public String toString() {
        return "jdbcUrl==>" + this.jdbcUrl + "\tloginTimeout==>" + this.loginTimeout + " seconds";
    }
}
 
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
 
public class ConfigureModule extends AbstractModule {
 
    @Override
    protected void configure() {
        bind(String.class)
            .annotatedWith(Names.named("JDBC URL"))
            .toInstance("jdbc:mysql://localhost/pizza");
        bind(Integer.class)
            .annotatedWith(Names.named("login timeout seconds"))
            .toInstance(10);        
    }
 
}
 
import com.google.inject.Guice;
import com.google.inject.Injector;
 
public class Test {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new ConfigureModule());
        Configure configure = injector.getInstance(Configure.class);
        System.out.println(configure);
    }
}

执行结果:
jdbcUrl==>jdbc:mysql://localhost/pizza    loginTimeout==>10 seconds

下一节:@Provides Methods


说明:

      鉴于网上guice中文资料较少,出于个人爱好,对该项目下的用户API文档进行翻译。如有翻译不恰当之处,还望指正。

      google Guice 项目地址:https://github.com/google/guice

      Guice 英文API地址:https://github.com/google/guice/wiki/LinkedBindings

分享到:

发表评论

昵称

沙发空缺中,还不快抢~