1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.inject.api;
18
19 import java.lang.annotation.Annotation;
20 import java.lang.reflect.Field;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import org.apache.commons.inject.api.bind.IBinder;
25 import org.apache.commons.inject.api.bind.IModule;
26 import org.apache.commons.inject.api.bind.IBinder.IInjectionParticipator;
27 import org.apache.commons.inject.util.Exceptions;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 public abstract class AbstractLoggerInjectingModule<Log> implements IModule {
44
45 @Override
46 public void configure(IBinder pBinder) {
47 pBinder.add(new IInjectionParticipator() {
48 @Override
49 public List<IPoint<Object>> getPoints(IKey<?> pKey, Class<?> pType) {
50 final List<IPoint<Object>> points = new ArrayList<IPoint<Object>>();
51 final Field[] fields = pType.getDeclaredFields();
52 final Class<? extends Annotation> annotationClass = getAnnotationClass();
53 for (final Field f : fields) {
54 if (f.isAnnotationPresent(annotationClass)) {
55 final Annotation annotation = f.getAnnotation(annotationClass);
56 String id = getId(annotation, f.getDeclaringClass());
57 if (id == null || id.length() == 0) {
58 id = f.getDeclaringClass().getName();
59 }
60 final Log logger = newLogger(id);
61 points.add(new IPoint<Object>(){
62 @Override
63 public void injectTo(Object pInstance,
64 IInjector pInjector) {
65 try {
66 if (!f.isAccessible()) {
67 f.setAccessible(true);
68 }
69 f.set(pInstance, logger);
70 } catch (Throwable t) {
71 throw Exceptions.show(t);
72 }
73 }
74 });
75 }
76 }
77 return points;
78 }
79 });
80 }
81
82
83
84
85
86 protected abstract Log newLogger(String pId);
87
88
89
90
91
92 protected Class<? extends Annotation> getAnnotationClass() {
93 return InjLogger.class;
94 }
95
96
97
98
99
100 protected String getId(Annotation pAnnotation, Class<?> pClass) {
101 final InjLogger injLogger = (InjLogger) pAnnotation;
102 final String id = injLogger.id();
103 if (id == null || id.length() == 0) {
104 return pClass.getName();
105 } else {
106 return id;
107 }
108 }
109 }