File: BindingToUnqualifiedCommonType.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (40 lines) | stat: -rw-r--r-- 1,351 bytes parent folder | download | duplicates (2)
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
Guice bindings are keyed by a pair of (optional Annotation, Type).

In most cirumstances, one doesn't need the annotation, as there's really just
one active implementation:

```java
bind(CoffeeMaker.class).to(RealCoffeeMaker.class);
...
@Inject Office(CoffeeMaker coffeeMaker) {}
```

However, in other circumstances, you want to bind a simple value (an integer,
String, double, etc.). You should use a Qualifier annotation to allow you to get
the *right* Integer back:

```java
bindConstant().annotatedWith(HttpPort.class).to(80);
...
@Inject MyWebServer(@HttpPort Integer httpPort) {}
```

NOTE: Make sure that your annotation has the [`@Qualifier`] meta-annotation on
it, otherwise injection systems can't see them. Guice users can optionally use
[`@BindingAnnotation`], but Guice also understands `@Qualifier`.

This works great, but if your integer binding *doesn't* include a Qualifier, it
just means that you can ask Guice for "the Integer", and it will give you a
value back:

```java
bind(Integer.class).toInstance(80);
...
@Inject MyWebServer(Integer httpsPort) {}
```

To avoid confusion in these circumstances, please use a Qualifier annotation
when binding simple value types.

[`@Qualifier`]: http://docs.oracle.com/javaee/6/api/javax/inject/Qualifier.html
[`@BindingAnnotation`]: https://github.com/google/guice/wiki/BindingAnnotations