Skip to content

Commit e6679cb

Browse files
authored
[ADD] [Spring] @bean @configuration @Component.md
1 parent 5de19c5 commit e6679cb

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# @Bean @Configuration @Component
2+
3+
@Bean vs. @Configuration vs. @Component 의 차이는?
4+
5+
스프링이 개발자 대신 객체를 제어하기 위해서는 객체들이 **Bean**으로 등록되어있어야 한다.
6+
7+
스프링 MVC에서는 `@Controller`, `@Service`, `@Repository` 등으로 Bean으로 등록할 수 있으며, configuration 관련 객체들은 `@Bean``@Component` 로 스프링 컨테이너에 객체를 Bean으로 등록할 수 있다.
8+
9+
## @Bean @Component @Configuration
10+
@Bean은 메소드 레벨에서 선언하며, 반환되는 객체(인스턴스)를 개발자가 **수동**으로 Bean으로 등록하는 annotation이다.
11+
12+
반면 @Component는 클래스 레벨에서 선언함으로써 스프링이 런타임시에 컴포넌트스캔을 하여 **자동**으로 Bean을 찾고(detect) 등록하는 annotation이다.
13+
(ClassPathBeanDefinitionScanner.java)
14+
15+
@Configuration은 외부라이브러리 또는 내장 클래스를 Bean으로 등록하고자 할 경우 사용한다. 1개 이상의 @Bean을 제공하는 클래스의 경우 반드시 @Configuration을 사용한다.
16+
17+
## @Bean @Component @Configuration Annotation
18+
### @Bean
19+
@Target은 METHOD
20+
```java
21+
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
22+
@Retention(RetentionPolicy.RUNTIME)
23+
@Documented
24+
public @interface Bean {
25+
//
26+
}
27+
```
28+
29+
### @Component
30+
@Target이 Type으로 지정되어 Class나 Interface에만 선언 가능
31+
```java
32+
@Target(ElementType.TYPE)
33+
@Retention(RetentionPolicy.RUNTIME)
34+
@Documented
35+
public @interface Bean {
36+
//
37+
}
38+
```
39+
40+
### @Configuration
41+
@Component annotation 포함
42+
```java
43+
@Target({ElementType.TYPE})
44+
@Retention(RetentionPolicy.RUNTIME)
45+
@Documented
46+
@Component
47+
public @interface Configuration {
48+
//
49+
}
50+
```
51+
52+
### 참고
53+
* [Spring Bean과 Componen의 차이](https://velog.io/@albaneo0724/Spring-%EC%8A%A4%ED%94%84%EB%A7%81-Bean%EA%B3%BC-Component%EC%9D%98-%EC%B0%A8%EC%9D%B4)
54+
* [Spring Component와 Configuration의 차이](https://velog.io/@albaneo0724/Spring-Component%EC%99%80-Configuration%EC%9D%98-%EC%B0%A8%EC%9D%B4)
55+
* [Bean과 Component 차이](https://youngjinmo.github.io/2021/06/bean-component/)

0 commit comments

Comments
 (0)