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