Skip to content

Commit

Permalink
feat: DI Stage3 통과
Browse files Browse the repository at this point in the history
  • Loading branch information
gitchannn committed Sep 26, 2023
1 parent a5ce3bd commit 4f9b7ab
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
42 changes: 40 additions & 2 deletions study/src/test/java/di/stage3/context/DIContainer.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package di.stage3.context;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;
import java.util.stream.Collectors;

/**
* 스프링의 BeanFactory, ApplicationContext에 해당되는 클래스
Expand All @@ -10,11 +14,45 @@ class DIContainer {
private final Set<Object> beans;

public DIContainer(final Set<Class<?>> classes) {
this.beans = Set.of();
this.beans = classes.stream()
.map(this::createInstance)
.collect(Collectors.toSet());
for (Object bean : this.beans) {
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
Object object = getBean(field.getType());
if (object == null) {
return;
}
try {
field.setAccessible(true);
field.set(bean, object);
field.setAccessible(false);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}

private Object createInstance(Class<?> aClass) {
try {
Constructor<?> constructor = aClass.getDeclaredConstructor();
constructor.setAccessible(true);
Object instance = constructor.newInstance();
constructor.setAccessible(false);
return instance;
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
InvocationTargetException e) {
throw new RuntimeException(e);
}
}

@SuppressWarnings("unchecked")
public <T> T getBean(final Class<T> aClass) {
return null;
return (T) beans.stream()
.filter(aClass::isInstance)
.findAny()
.orElse(null);
}
}
2 changes: 1 addition & 1 deletion study/src/test/java/di/stage3/context/Stage3Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Stage3Test {
void stage3() {
final var user = new User(1L, "gugu");

final var diContainer = createDIContainer();
DIContainer diContainer = createDIContainer();

/**
* 제어의 역전(IoC)
Expand Down

0 comments on commit 4f9b7ab

Please sign in to comment.