๋ชฉ์ฐจ
- ๋น ์๋ช ์ฃผ๊ธฐ์ ์ฃผ์๋จ๊ณ
- Bean ์ด๊ธฐํ ๋ฐฉ๋ฒ
- Bean ์๋ฉธ ๊ณผ์
โ ๋น ์๋ช ์ฃผ๊ธฐ์ ์ฃผ์ ๋จ๊ณ
- ๊ฐ์ฒด ์์ฑ -> @Component, @Bean๋ฑ์ ํตํด Bean ์์ฑ
- ์์กด์ฑ ์ฃผ์ (DI, Dependency Injection) -> ํ์ํ ์์กด์ฑ์ด ์ฃผ์ ๋จ
- ์ด๊ธฐํ ๊ณผ์ -> @PostConstruct, InitializingBean, init-method ๋ฑ์ ์ฌ์ฉํ์ฌ ์ด๊ธฐ ์ค์ ์ํ
- ์ฌ์ฉ(Usage) -> ์ ์์ ์ผ๋ก ๋น์ด ์ฌ์ฉ๋จ
- ์๋ฉธ(Destruction) -> @PreDestroy, DisposableBean, destroy-method ๋ฑ์ ์ฌ์ฉํ์ฌ ์ ๋ฆฌ ์์ ์ํ
- Garbage Collection -> Spring ์ปจํ ์ด๋์์ ๋ ์ด์ ๊ด๋ฆฌํ์ง ์์ผ๋ฉด GC๋์์ด ๋จ
โ Bean ์ด๊ธฐํ ๋ฐฉ๋ฒ
1๏ธโฃ @PostConstruct (๊ฐ์ฅ ๋ง์ด ์ฌ์ฉ)
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("MyBean์ด ์ด๊ธฐํ๋์์ต๋๋ค!");
}
}
- Bean์ด ์์ฑ๋ ํ ์๋์ผ๋ก ์คํ๋จ
- ๊ฐ์ฅ ๋ง์ด ์ฌ์ฉ๋๋ฉฐ @Component, @Service, @Repository๋ฑ๊ณผ ํจ๊ป ์ฌ์ฉ๊ฐ๋ฅ
2๏ธโฃ InitializingBean ์ธํฐํ์ด์ค ๊ตฌํ
@Component
public class MyBean implements InitializingBean {
@Override
public void afterPropertiesSet() {
System.out.println("MyBean ์ด๊ธฐํ - afterPropertiesSet ์คํ๋จ!");
}
}
- afterPropertiesSet() ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉ ํ์ฌ ์ด๊ธฐํ ๋ก์ง์ ์ ์
- Spring ์ ์ฉ ์ธํฐํ์ด์ค๋ผ์ ๊ฐํ ๊ฒฐํฉ๋๊ฐ ์๊ธธ ์ ์์
3๏ธโฃ @Bean ๋ฑ๋ก์ initMethod ์ง์
@Bean(initMethod = "init")
public MyBean myBean() {
return new MyBean();
}
- @Bean๋ฐฉ์์ผ๋ก ๋ฑ๋กํ ๋ ์ง์ ์ด๊ธฐํ ๋ฉ์๋ ์ง์ ๊ฐ๋ฅ
โ Bean ์๋ฉธ(Destroy) ๊ณผ์
* Spring Boot์์๋ Bean์ด ์ ๊ฑฐ๋ ๋ ๋ฆฌ์์ค ํด์ ์ ๊ฐ์ด ํ์ํ ์ ๋ฆฌ ์์ ์ ์ํํ ์ ์๋ค. *
1๏ธโฃ @PreDestroy(๊ฐ์ฅ ๋ง์ด ์ฌ์ฉ)
@Component
public class MyBean {
@PreDestroy
public void destroy() {
System.out.println("MyBean์ด ์๋ฉธ๋ฉ๋๋ค!");
}
}
- Spring ์ปจํ ์ด๋๊ฐ ์ข ๋ฃ๋ ๋ ApplicaionContext.close() ์ด ์คํ๋จ
2๏ธโฃ DisposableBean ์ธํฐํ์ด์ค ๊ตฌํ
@Component
public class MyBean implements DisposableBean {
@Override
public void destroy() {
System.out.println("MyBean ์๋ฉธ - destroy ์คํ๋จ!");
}
}
- destory() ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํ์ฌ ๋ฆฌ์์ค ์ ๋ฆฌ ๊ฐ๋ฅ
3๏ธโฃ @Bean๋ฑ๋ก์ destroyMethod ์ง์
@Bean(destroyMethod = "cleanup")
public MyBean myBean() {
return new MyBean();
}
- ํน์ ๋ฉ์๋๋ฅผ ์๋ฉธ ๋จ๊ณ์์ ์คํํ๋๋ก ์ค์ ๊ฐ๋ฅ
๐ก ๊ฒฐ๋ก :
- Spring Boot์์๋ Bean์ด ์์ฑ๋๊ณ ์ ๊ฑฐ๋ ๋๊น์ง์ ํ๋ฆ์ ์๋ช ์ฃผ๊ธฐ๋ผ๊ณ ํ๋ค.
- Bean์ ์์ฑ -> ์์กด์ฑ ์ฃผ์ -> ์ด๊ธฐํ -> ์ฌ์ฉ -> ์๋ฉธ ๋จ๊ณ๋ฅผ ๊ฑฐ์น๋ค.
- Spring์ด Bean ์๋ช ์ฃผ๊ธฐ๋ฅผ ๊ด๋ฆฌํ๋ ์ด์ ๋ ๊ฐ์ฒด ๊ด๋ฆฌ๋ฅผ ์๋ํํ์ฌ ๊ฐ๋ฐ์์ ๋ถ๋ด์ ์ค์ด๊ธฐ ์ํจ์ด๋ค.
- @PostConstruct(์์ฑ ๊ณผ์ )์ @PreDestroy(์๋ฉธ ๊ณผ์ )๊ฐ ๊ฐ์ฅ ๋ง์ด ์ฌ์ฉ๋๋ค.
- InitializingBean๊ณผ DisposableBean์ ๊ฐํ ๊ฒฐํฉ๋๋ฅผ ๊ฐ์ ธ ์ผ๋ฐ์ ์ผ๋ก ์ ์ฌ์ฉํ์ง ์๋๋ค.
- @Bean(initMethod, detroyMethod)๋ฅผ ํ์ฉํ๋ฉด ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ด๊ธฐํ ๋๋ ์๋ฉธ ๊ด๋ฆฌ ๊ฐ๋ฅํ๋ค.
'๋ฐฑ์๋ > Spring boot' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Entity ์์ ์กฐ๊ฑด์ ์๋์ผ๋ก ๋ถ์ฌ์ฃผ๋ ๋ฐฉ๋ฒ๋ค (@SQLRestriction, @Where, @Filter) (0) | 2025.04.14 |
---|---|
Feign Client ํธ์ถ ์๋ต Dto์ ํ๋๋ช ์ด ๋ค๋ฅผ๋ (0) | 2025.04.14 |
API Gateway ์ Kafka (0) | 2025.02.26 |
Spring Boot ๋ฉํฐ ๋ชจ๋ ํ๋ก์ ํธ ์ค๊ณ (0) | 2025.02.25 |
EC2์์ PostgreSQL์ Docker๋ก ์ด์ํ๋ฉฐ ๊ฒช์๋ ์ค๋ฅ ํด๊ฒฐ ๊ณผ์ ์ ๋ฆฌ (0) | 2025.02.14 |