1
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
1
2
import static org .junit .jupiter .api .Assertions .assertThrows ;
2
3
3
4
import com .google .inject .AbstractModule ;
4
5
import com .google .inject .Guice ;
5
6
import com .google .inject .Injector ;
6
7
import java .lang .annotation .Annotation ;
8
+ import java .lang .annotation .ElementType ;
9
+ import java .lang .annotation .Retention ;
10
+ import java .lang .annotation .RetentionPolicy ;
11
+ import java .lang .annotation .Target ;
7
12
import javax .inject .Inject ;
8
13
import javax .inject .Named ;
14
+ import javax .inject .Qualifier ;
15
+ import model .Car ;
16
+ import model .Engine ;
17
+ import model .EngineV6 ;
18
+ import model .EngineV8 ;
9
19
import org .junit .jupiter .api .Assertions ;
10
20
import org .junit .jupiter .api .Test ;
11
21
15
25
*/
16
26
public class NamedInjectTest {
17
27
18
- interface Engine {
19
-
20
- String name ();
21
- }
22
-
23
- interface Car {
24
-
25
- Engine getEngine ();
26
- }
27
-
28
28
static class CarWithNamedInject implements Car {
29
29
30
30
@ Inject
@@ -45,22 +45,6 @@ public Class<? extends Annotation> annotationType() {
45
45
}
46
46
}
47
47
48
- static class EngineV8 implements Engine {
49
-
50
- @ Override
51
- public String name () {
52
- return "V8" ;
53
- }
54
- }
55
-
56
- static class EngineV6 implements Engine {
57
-
58
- @ Override
59
- public String name () {
60
- return "V6" ;
61
- }
62
- }
63
-
64
48
@ Test
65
49
public void should_injected_by_named () {
66
50
Injector injector = Guice .createInjector (new AbstractModule () {
@@ -85,4 +69,45 @@ protected void configure() {
85
69
}));
86
70
}
87
71
72
+ @ Qualifier
73
+ @ Target ({ElementType .CONSTRUCTOR , ElementType .FIELD , ElementType .METHOD })
74
+ @ Retention (RetentionPolicy .RUNTIME )
75
+ public @interface Super {
76
+
77
+ }
78
+
79
+ record SuperEngine () implements Super {
80
+
81
+ @ Override
82
+ public Class <? extends Annotation > annotationType () {
83
+ return Super .class ;
84
+ }
85
+ }
86
+
87
+ static class SuperEngineCar implements Car {
88
+
89
+ @ Inject
90
+ @ Super
91
+ Engine engine ;
92
+
93
+ @ Override
94
+ public Engine getEngine () {
95
+ return engine ;
96
+ }
97
+ }
98
+
99
+ @ Test
100
+ public void should_inject_by_special_annotation () {
101
+ Injector injector = Guice .createInjector (new AbstractModule () {
102
+ @ Override
103
+ protected void configure () {
104
+ bind (Engine .class ).annotatedWith (new SuperEngine ()).to (EngineV8 .class );
105
+ bind (Car .class ).to (SuperEngineCar .class );
106
+ }
107
+ });
108
+
109
+ Car car = injector .getInstance (Car .class );
110
+ assertEquals (new EngineV8 ().name (), car .getEngine ().name ());
111
+ }
112
+
88
113
}
0 commit comments