| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
package org.dozer.inject; |
| 17 | |
|
| 18 | |
import org.dozer.MappingException; |
| 19 | |
import org.dozer.util.ReflectionUtils; |
| 20 | |
|
| 21 | |
import java.lang.reflect.Field; |
| 22 | |
import java.util.Collection; |
| 23 | |
import java.util.HashSet; |
| 24 | |
import java.util.Map; |
| 25 | |
import java.util.concurrent.ConcurrentHashMap; |
| 26 | |
|
| 27 | |
|
| 28 | |
|
| 29 | |
|
| 30 | 7 | public class DozerBeanContainer implements BeanRegistry { |
| 31 | |
|
| 32 | 7 | private Map<Class<?>, Object[]> beans = new ConcurrentHashMap<Class<?>, Object[]>(); |
| 33 | |
|
| 34 | |
public void register(Class<?> type) { |
| 35 | 8 | beans.put(type, new Object[1]); |
| 36 | 8 | } |
| 37 | |
|
| 38 | |
public <T> T getBean(Class<T> type) { |
| 39 | 7 | Collection<T> result = getBeans(type); |
| 40 | 7 | if (result.isEmpty()) { |
| 41 | 1 | throw new IllegalStateException("Bean is not registered : " + type.getName()); |
| 42 | |
} |
| 43 | 6 | if (result.size() > 1) { |
| 44 | 1 | throw new IllegalStateException("More than one bean found of type : " + type.getName()); |
| 45 | |
} |
| 46 | |
|
| 47 | 5 | return result.iterator().next(); |
| 48 | |
} |
| 49 | |
|
| 50 | |
public <T> Collection<T> getBeans(Class<T> type) { |
| 51 | 8 | HashSet<T> result = new HashSet<T>(); |
| 52 | 8 | for (Map.Entry<Class<?>, Object[]> entry : beans.entrySet()) { |
| 53 | 11 | if (type.isAssignableFrom(entry.getKey())) { |
| 54 | 9 | Object[] value = entry.getValue(); |
| 55 | 9 | if (value[0] == null) { |
| 56 | 8 | value[0] = wireBean(entry.getKey()); |
| 57 | |
} |
| 58 | 9 | result.add((T) value[0]); |
| 59 | |
} |
| 60 | 11 | } |
| 61 | 8 | return result; |
| 62 | |
} |
| 63 | |
|
| 64 | |
private <T> T wireBean(Class<T> type) { |
| 65 | 13 | final T bean = ReflectionUtils.newInstance(type); |
| 66 | |
|
| 67 | 13 | Field[] destFields = type.getDeclaredFields(); |
| 68 | 64 | for (Field field : destFields) { |
| 69 | 51 | Inject inject = field.getAnnotation(Inject.class); |
| 70 | 51 | if (inject != null) { |
| 71 | 5 | Class<?> fieldType = field.getType(); |
| 72 | |
try { |
| 73 | 5 | if (field.get(bean) == null) { |
| 74 | 5 | Object dependency = wireBean(fieldType); |
| 75 | 5 | field.set(bean, dependency); |
| 76 | |
} |
| 77 | 0 | } catch (IllegalAccessException e) { |
| 78 | 0 | throw new MappingException("Field annotated with @Inject is not accessible : " + field.getName(), e); |
| 79 | 5 | } |
| 80 | |
} |
| 81 | |
} |
| 82 | |
|
| 83 | 13 | Object[] instance = beans.get(type); |
| 84 | 13 | if (instance == null) { |
| 85 | 5 | instance = new Object[1]; |
| 86 | 5 | beans.put(type, instance); |
| 87 | |
} |
| 88 | 13 | instance[0] = bean; |
| 89 | 13 | return bean; |
| 90 | |
} |
| 91 | |
|
| 92 | |
} |