private void injectBeansToComponents() { for (Class<?> c : componentsClasses) { try { Object object = c.newInstance(); for (Field f : c.getDeclaredFields()) { if (f.isAnnotationPresent(Inject.class)) { f.setAccessible(true); Class<?> fieldClass = f.getType(); BeanDefinition beanDefinition = findBeenByClass(fieldClass); f.set(object, beanDefinition.getInstance()); } } preparedComponents.put(c.getName(), new SingletonBeanDefinition(c, object)); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } }
@Override public Object getComponent(Class<?> clazz) { Object objectToReturn = preparedComponents.get(clazz.getName()).getInstance(); if (objectToReturn != null) { return objectToReturn; } else { for (BeanDefinition definition : preparedComponents.values()) { if (Arrays.asList(definition.getClazz().getInterfaces()).contains(clazz)) { if (objectToReturn == null) { objectToReturn = definition.getInstance(); } else { throw new FailureComponentCreationException( "Can't resolve component to return, more than one component found, for class: " + clazz.getName()); } } } if (objectToReturn != null) { return objectToReturn; } else { throw new ComponentNotFoundException("Can't find component for class: " + clazz.getName()); } } }
private BeanDefinition findBeenByClass(Class<?> clazz) { BeanDefinition definitionToReturn = beans.get(clazz.getName()); if (definitionToReturn != null) { return definitionToReturn; // TODO Resolve more than one bean to inject bug in this case } else { for (BeanDefinition definition : beans.values()) { if (Arrays.asList(definition.getClazz().getInterfaces()).contains(clazz)) { if (definitionToReturn == null) { definitionToReturn = definition; } else { throw new FailureBeanInjectionException( "Can't resolve bean injection, more than one beanDefinition found, for class: " + clazz.getName()); } } } if (definitionToReturn != null) { return definitionToReturn; } else { throw new FailureBeanInjectionException( "Can't find bean to inject for class: " + clazz.getName()); } } }