๊ธฐ๋ณธ์ ์ผ๋ก ๋น ์ค์ฝํ๊ฐ ์ฑ๊ธํค์ผ๋ก ์์ฑ๋๋ฉด ์คํ๋ง ์ปจํ ์ด๋์ ์์ฑ ์์ ์ ๋น๋ ์์ฑ๋๊ณ ์คํ๋ง ์ปจํ ์ด๋์ ์๋ฉธ ์์ ์ ๋น๋ ์๋ฉธ๋๋ค.
๋ฐ๋ผ์ ํด๋น ๊ธ์์์ ๋น์ ์๋ช ์ฃผ๊ธฐ๋ ๋น ์ค์ฝํ๋ฅผ ์ฑ๊ธํค์ผ๋ก ์ค์ ํ์ ๋๋ผ๊ณ ๊ฐ์ ํ๋ค.
๋น ์ค์ฝํ๋ ํด๋น ๊ฒ์๋ฌผ ์ฐธ์กฐ
์คํ๋ง ์ปจํ ์ด๋๋ ์๋์ ๊ฐ์ด ์ด๊ธฐํ์ ์ข ๋ฃ๋ผ๋ ์๋ช ์ฃผ๊ธฐ๋ฅผ ๊ฐ๋๋ค.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
// 1. ์ปจํ
์ด๋ ์ด๊ธฐํ (์์ฑ)
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppContext.class);
// 2. ์ปจํ
์ด๋ ๋ด์ ๋ฑ๋ก๋ ๋น ์ฌ์ฉ
MyClass mc = context.getBean("myClass", MyClass.class);
mc.print();
// 3. ์ปจํ
์ด๋ ์ข
๋ฃ
context.close();
}
}
-
์ปจํ ์ด๋ ์ด๊ธฐํ
์คํ๋ง ์ปจํ ์ด๋๊ฐ ์์ฑ๋๋ค. ์คํ๋ง ์ปจํ ์ด๋๋ ์์ฑ์์ ์ธ์๋ก ์ ๋ฌ๋๋ ์ค์ ํด๋์ค(@Configuration์ด ์ ์ฉ๋ ํด๋์ค)์์ ์ ๋ณด๋ฅผ ์ฝ์ด์ ๋น์ ์์ฑํ๊ณ ์ฐ๊ฒฐ(์์กด์ฑ ์ฃผ์ )ํ๋ค.
-
์ปจํ ์ด๋ ์ฌ์ฉ
์ปจํ ์ด๋๊ฐ ์ด๊ธฐํ๋๊ณ ๋๋ฉด getBean์ ํตํด ๋ฑ๋ก๋ ๋น์ ์ด์ฉํ ์ ์๋ค.
-
์ปจํ ์ด๋ ์ข ๋ฃ
์ปจํ ์ด๋์ ์ฌ์ฉ์ด ๋๋๋ฉด ์ปจํ ์ด๋๋ฅผ ์ข ๋ฃํ๋ค. ์ด ๋ ๋น ๊ฐ์ฒด๋ ๋ชจ๋ ์๋ฉธํ๋ค.
์คํ๋ง ๋น์ ์๋ช ์ฃผ๊ธฐ๋ ์คํ๋ง ์ปจํ ์ด๋์ ์๋ช ์ฃผ๊ธฐ์ ์ํด ๊ด๋ฆฌ๋๋ค.
์คํ๋ง ๋น์ ์๋ช ์ฃผ๊ธฐ๋ ๋ค์์ 4๋จ๊ณ๋ก ๋๋ ์ ์๋ค.
- ๊ฐ์ฒด ์์ฑ โ ์คํ๋ง ์ปจํ ์ด๋ ์์ฑ๊ณผ ํจ๊ป ์์ฑ
- ์์กด ์ค์ โ ์คํ๋ง ์ปจํ ์ด๋์ ์์ฑ๊ณผ ํจ๊ป ์ค์
- ์ด๊ธฐํ โ 1,2๋ฒ์ด ์๋ฃ๋ ํ ์คํ๋ง ์ปจํ ์ด๋๊ฐ ๋น ๊ฐ์ฒด์ ์ด๊ธฐํ๋ฅผ ์ํ ์ง์ ๋ฉ์๋ ํธ์ถ
- ์๋ฉธ โ ์คํ๋ง ์ปจํ ์ด๋ ์ข ๋ฃ ์ ์คํ๋ง ์ปจํ ์ด๋๊ฐ ๋น ๊ฐ์ฒด์ ์๋ฉธ์ ์ํ ์ง์ ๋ฉ์๋ ํธ์ถ
-
์ด๊ธฐํ
InitializingBean ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ๋ค afterPropertiesSet ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํ๋ฉด ๋๋ค.
public interface InitializingBean { void afterPropertiesSet() throw Exception; }
-
์๋ฉธ
DisposableBean ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ๋ค destroy ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํ๋ฉด ๋๋ค.
public interface DisposableBean { void destroy() throw Exception; }
-
์์
package com.yihyun.introduction; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; @Component public class MyClass implements InitializingBean, DisposableBean { private String name; public void print() { System.out.println("hello " + name); } public void setName(String name) { this.name = name; } @Override public void afterPropertiesSet() throws Exception { System.out.println("myClass Bean ์ด๊ธฐํ"); } @Override public void destroy() throws Exception { System.out.println("myClass Bean ์๋ฉธ"); } }
๋ณดํต ๋น ๋ฑ๋ก์ ์ํด ๋น์ ์ํ์ด ๋๋ ํด๋์ค์ @Component ์ด๋ ธํ ์ด์ ์ ์ ์ฉํ์ง๋ง, ์ธ๋ถ์์ ์ ๊ณต๋ฐ์ ์์ค ์ฝ๋๊ฐ ์๋ ํด๋์ค์ ๊ฒฝ์ฐ์๋ @Configuration์์ ์ง์ ๋น์ผ๋ก ๋ฑ๋กํ๋ค.
์ด ๊ฒฝ์ฐ์๋ ์์ฒ๋ผ ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ์ ์์ผ๋ฏ๋ก ๋ค์๊ณผ ๊ฐ์ด ์ด๊ธฐํ์ ์๋ฉธ ๋ฉ์๋๋ฅผ ์ง์ ํ๋ฉด ๋๋ค.
@Bean(initMethod = "๋ฉ์๋๋ช
", destroyMethod = "๋ฉ์๋๋ช
")
public ExternalClass externalClass() {
return new ExternelClass();
}