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 package info.magnolia.objectfactory.guice;
35
36 import java.util.List;
37
38 import com.google.inject.Binding;
39 import com.google.inject.Injector;
40 import com.google.inject.Key;
41 import com.google.inject.TypeLiteral;
42 import com.google.inject.internal.Annotations;
43 import com.google.inject.internal.Errors;
44 import com.google.inject.internal.ErrorsException;
45
46 import info.magnolia.objectfactory.MgnlInstantiationException;
47 import info.magnolia.objectfactory.ParameterInfo;
48 import info.magnolia.objectfactory.ParameterResolver;
49
50
51
52
53
54
55
56 public class GuiceParameterResolver implements ParameterResolver {
57
58 private final Injector injector;
59
60 public GuiceParameterResolver(Injector injector) {
61 this.injector = injector;
62 }
63
64 public GuiceParameterResolver(GuiceComponentProvider componentProvider) {
65 this.injector = componentProvider.getInjector();
66 }
67
68 @Override
69 public Object resolveParameter(ParameterInfo parameter) {
70
71
72
73
74 Key<?> key = getKey(parameter);
75 Binding<?> existingBinding = injector.getExistingBinding(key);
76 return existingBinding != null ? existingBinding.getProvider().get() : UNRESOLVED;
77 }
78
79 private Key<?> getKey(ParameterInfo parameter) {
80 try {
81
82
83 TypeLiteral<?> declaringType = TypeLiteral.get(parameter.getDeclaringClass());
84 List<TypeLiteral<?>> parameterTypes = declaringType.getParameterTypes(parameter.getConstructor());
85 TypeLiteral<?> parameterType = parameterTypes.get(parameter.getParameterIndex());
86
87
88 Errors errors = new Errors(parameter.getConstructor());
89 return Annotations.getKey(
90 parameterType,
91 parameter.getConstructor(),
92 parameter.getParameterAnnotations(),
93 errors);
94
95 } catch (ErrorsException e) {
96 throw new MgnlInstantiationException(e.getMessage(), e);
97 }
98 }
99 }