1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
package org.apache.shiro.guice.web; |
20 | |
|
21 | |
import com.google.common.collect.ImmutableSet; |
22 | |
import com.google.inject.Inject; |
23 | |
import com.google.inject.Injector; |
24 | |
import com.google.inject.Key; |
25 | |
import com.google.inject.ProvisionException; |
26 | |
import com.google.inject.spi.Dependency; |
27 | |
import com.google.inject.spi.InjectionPoint; |
28 | |
import com.google.inject.spi.ProviderWithDependencies; |
29 | |
|
30 | |
import java.lang.reflect.Constructor; |
31 | |
import java.util.Set; |
32 | |
|
33 | |
class AbstractInjectionProvider<T> implements ProviderWithDependencies<T> { |
34 | |
private Key<T> key; |
35 | |
|
36 | |
@Inject |
37 | |
Injector injector; |
38 | |
|
39 | |
private InjectionPoint constructorInjectionPoint; |
40 | |
private Set<Dependency<?>> dependencies; |
41 | |
|
42 | 7 | public AbstractInjectionProvider(Key<T> key) { |
43 | 7 | this.key = key; |
44 | 7 | constructorInjectionPoint = InjectionPoint.forConstructorOf(key.getTypeLiteral()); |
45 | |
|
46 | 7 | ImmutableSet.Builder<Dependency<?>> dependencyBuilder = ImmutableSet.builder(); |
47 | 7 | dependencyBuilder.addAll(constructorInjectionPoint.getDependencies()); |
48 | 7 | for (InjectionPoint injectionPoint : InjectionPoint.forInstanceMethodsAndFields(key.getTypeLiteral())) { |
49 | 6 | dependencyBuilder.addAll(injectionPoint.getDependencies()); |
50 | |
} |
51 | 7 | this.dependencies = dependencyBuilder.build(); |
52 | 7 | } |
53 | |
|
54 | |
public T get() { |
55 | 5 | Constructor<T> constructor = getConstructor(); |
56 | 5 | Object[] params = new Object[constructor.getParameterTypes().length]; |
57 | 5 | for (Dependency<?> dependency : constructorInjectionPoint.getDependencies()) { |
58 | 2 | params[dependency.getParameterIndex()] = injector.getInstance(dependency.getKey()); |
59 | |
} |
60 | |
T t; |
61 | |
try { |
62 | 5 | t = constructor.newInstance(params); |
63 | 0 | } catch (Exception e) { |
64 | 0 | throw new ProvisionException("Could not instantiate " + key + "", e); |
65 | 5 | } |
66 | 5 | injector.injectMembers(t); |
67 | 5 | return postProcess(t); |
68 | |
} |
69 | |
|
70 | |
@SuppressWarnings({"unchecked"}) |
71 | |
private Constructor<T> getConstructor() { |
72 | 5 | return (Constructor<T>) constructorInjectionPoint.getMember(); |
73 | |
} |
74 | |
|
75 | |
protected T postProcess(T t) { |
76 | |
|
77 | 1 | return t; |
78 | |
} |
79 | |
|
80 | |
public Set<Dependency<?>> getDependencies() { |
81 | 1 | return dependencies; |
82 | |
} |
83 | |
} |