From 4f9b7ab878885ebad6ad76079a6d042a68cd0cc6 Mon Sep 17 00:00:00 2001 From: gitchan Date: Tue, 26 Sep 2023 15:17:42 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20DI=20Stage3=20=ED=86=B5=EA=B3=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/di/stage3/context/DIContainer.java | 42 ++++++++++++++++++- .../java/di/stage3/context/Stage3Test.java | 2 +- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/study/src/test/java/di/stage3/context/DIContainer.java b/study/src/test/java/di/stage3/context/DIContainer.java index b62feb1ed3..db13a1b613 100644 --- a/study/src/test/java/di/stage3/context/DIContainer.java +++ b/study/src/test/java/di/stage3/context/DIContainer.java @@ -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에 해당되는 클래스 @@ -10,11 +14,45 @@ class DIContainer { private final Set beans; public DIContainer(final Set> 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 getBean(final Class aClass) { - return null; + return (T) beans.stream() + .filter(aClass::isInstance) + .findAny() + .orElse(null); } } diff --git a/study/src/test/java/di/stage3/context/Stage3Test.java b/study/src/test/java/di/stage3/context/Stage3Test.java index 2363e8666f..c1451aaa44 100644 --- a/study/src/test/java/di/stage3/context/Stage3Test.java +++ b/study/src/test/java/di/stage3/context/Stage3Test.java @@ -19,7 +19,7 @@ class Stage3Test { void stage3() { final var user = new User(1L, "gugu"); - final var diContainer = createDIContainer(); + DIContainer diContainer = createDIContainer(); /** * 제어의 역전(IoC)