原文地址:https://code.google.com/p/google-guice/wiki/InstanceBindings
InstanceBindings(实例绑定):基本类型直接绑定值。
贴代码:
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
|
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"
))
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