原文地址:https://code.google.com/p/google-guice/wiki/ProvidesMethods
@Provides Methods(@Provides注解方法):用@Provides来注解方法产生需要的对象。
贴代码:
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, 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.Provides; 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"); } @Provides int getLoginTimeout() { System.out.println("run @Provides"); return 20; } } 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); } }
执行结果:
run @Provides
jdbcUrl==>jdbc:mysql://localhost/pizza loginTimeout==>20 seconds
可以看到,在module里没有绑定int类型的值,却在依赖时注入了。