03. Bean ๋ฑ๋ก (JAVA)
JAVA Class ๋ฅผ ํ์ฉํ์ฌ Bean ์ ๋ฑ๋กํ๋ ๋ฐฉ๋ฒ์ ์์๋ณด์ ๐๐ปโโ๏ธ
1๏ธโฃ ย src/main/java
โ๏ธ Bean ๋ฑ๋ก ์ค์ต์ ์งํํ class ์ ๋ณด
2๏ธโฃ ย BeanClass.java
โ๏ธ Bean ์ ๋ฑ๋กํ๋ ค๋ฉด Class ์๋จ์ @Configuration ์ด๋ ธํ ์ด์ ์ ์ถ๊ฐํด์ผ ํ๋ค. (ํด๋น ์๋ฐ ํ์ผ์ด Bean ๋ฑ๋ก์ ์ํ ํ์ผ์์ ์๋ฆฌ๋ ๊ฒ)
package config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanClass {
}
Bean ๐ ์ ๋ฑ๋กํ๋ ค๋ฉด @Bean ์ ์ ์ด๋ฃ์ด์ผ ํ๋ค. ๋ฉ์๋ ํ์์ผ๋ก ์์ฑํ๋ฉฐ, ๋ฉ์๋๋ช ์ด ํด๋น Bean ์ name ์ด ๋๋ค.
Bean ๐ฅ ์ name์ ์ง์ ์ ๋ ฅํ ์๋ ์๋ค. ์ด ๊ฒฝ์ฐ ๋ฉ์๋๋ช (avoavo)์ด ์๋ name(avocado) ์ผ๋ก ํธ์ถํด์ผ ํ๋ค.
@Configuration
public class BeanClass {
@Bean
public Cart cart() {
return new Cart();
}
@Bean(name="avocado")
public Avocado avoavo() {
return new Avocado();
}
}
- Bean ์ ๋ฑ๋กํ๋ค๋ฉด main ์์ (1) Configuration ์ด๋ ธํ ์ด์ ์ด ๋ถ์ด์๋ ํด๋์ค๋ฅผ ํ์ฑํ๊ณ , (2) @Bean ์ด ์๋ ๋ฉ์๋๋ฅผ ์ฐพ์์ ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.
public class Main {
public static void main(String[] args) {
//(1)
AnnotationConfigApplicationContext atx = new AnnotationConfigApplicationContext(BeanClass.class);
//(2)
Cart cart = atx.getBean("cart", Cart.class);
}
}
๐ก @Configuration ํด๋์ค๋ฅผ ๋ก๋ฉํ ๋ Bean ์ด ์์ฑ๋๋ฉฐ, getBean() ๋ฉ์๋๋ ์์ฑ๋ ๊ฐ์ฒด์ ์ฃผ์๊ฐ์ ๋ถ๋ฌ์ค๋ ์์ ์ ํ๋ค. ๋ํ Bean ์ Singleton ์ผ๋ก ์์ฑ๋๋ค.
3๏ธโฃ ย @lazy
โ๏ธ ๊ฐ์ฒด ์์ฑ ์๊ธฐ๋ฅผ ์กฐ์ ํ ์ ์๋ค. ์๋ฌด๋ฐ ์ค์ ์ ์ฃผ์ง ์์ผ๋ฉด Configuration ํด๋์ค๋ฅผ ๋ก๋ฉํ ๋ ๊ฐ์ฒด๊ฐ ์์ฑ๋์ง๋ง, @Lazy ์ด๋ ธํ ์ด์ ์ ๋ถ์ด๋ฉด getBean() ๋ฉ์๋๋ก ํธ์ถํ ๋ ๊ฐ์ฒด๊ฐ ์์ฑ๋๋ค.
@Bean(name="avocado")
@Lazy
public Avocado avoavo() {
return new Avocado();
}
4๏ธโฃ ย @scope
โ๏ธ @scope(โprototypeโ) ์ผ๋ก ์ค์ ํ๋ฉด, ๊ฐ์ฒด ์์ฑ ์๊ธฐ๋ฅผ getBean() ๋ฉ์๋๋ก ํธ์ถํ ๋๋ก ๋ฆ์ถ ์ ์์ผ๋ฉด์ Singleton ์ผ๋ก ์์ฑ๋์ง ์๋๋ก ํ๋ค.
@Bean
@Scope("prototype")
public Jumeokbap jumeokbap() {
return new Jumeokbap();
}
5๏ธโฃ ย @PostConstruct
โ๏ธ init-method ์ ๊ฐ์ ๊ฐ๋ ์ผ๋ก, ์ด๊ธฐํ ์ฝ๋ฐฑ์ ํ๊ณ ์ ํ๋ ๋ฉ์๋์ ์ฌ์ฉํ๋ ์ด๋ ธํ ์ด์ ์ด๋ค.
โ๏ธ ์ด๊ธฐํ ์ฝ๋ฐฑ์ด๋ ์คํ๋ง ๋น์ด ์์ฑ๋๊ณ , ๋น์ ์์กด๊ด๊ณ ์ฃผ์ ์ด ์๋ฃ๋ ์ดํ์ ํธ์ถ๋๋ ๋ฉ์๋๋ฅผ ๋งํ๋ค.
@Controller
public class BasicItemController {
@PostConstruct
public void init() {
itemRepository.save(new Item("itemA", 10000, 10));
itemRepository.save(new Item("itemB", 30000, 30));
}
}
6๏ธโฃ ย @PreDestroy
- destroy-method ์ ๊ฐ์ ๊ฐ๋ ์ผ๋ก, ํด๋น ์ด๋ ธํ ์ด์ ์ ๋ฌ๊ณ ์๋ ๋ฉ์๋๋ ๋น์ด ์๋ฉธ๋๊ธฐ ์ง์ ์ ํธ์ถ๋๋ค.
@Controller
public class BasicItemController {
@PreDestroy
public void init() {
itemRepository.clear();
}
}