[DEV] J-Jay

스프링 부트 코드 이해 (2) 본문

Back-end/Spring

스프링 부트 코드 이해 (2)

J-Jay 2023. 8. 31. 23:19
728x90

TestController

@RestController
public class TestController {
    @GetMapping("/test") // /test GET 요청이 오면 test() 메서드 실행
    public String test() {
        return "Hello, world";
    }
}

@RestController는 라우터 역할을 하는 어노테이션이다. (라우터 : HTTP 요청과 메서드를 연결하는 장치)

해당 어노테이션이 있어야 클러이언트의 요청에 맞는 메서드를 실행할 수 있다.

지금의 경우 TestController를 라우터로 지정해 /test GET 요청이 왔을 때 test() 메서드를 실행한다.

여기서 의문이 하나 생긴다 @RestController와 @Component는 어노테이션 용어가 다른데 어떻게 같은 @Component처럼 취급하는 걸까?

 

직접 살펴보자.

 

1단계 : @RestController

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";

}

코드를 보면 @Controller, @ResponseBody 어노테이션이 함께있다. 

말 그대로 @RestController는 @Controller + @ResponseBody 합쳐진 결과물이다. 중요한 건 @Component가 없다.

 


2단계 : @Controller

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}

드디어 @Component 어노테이션을 찾았다.

이를 통해 @Controller 어노테이션이 @ComponentScan을 통해 빈으로 등록되는 이유를 찾았고 추가적으로

@Configuration, @Repository, @Service 어노테이션 모두 @Component 어노테이션을 가지고 있다.

다만 빈이 무슨 역할을 하는지 명확하게 구분하기 위해 다름 이름으로 설정되어 있을 뿐이다.

'Back-end > Spring' 카테고리의 다른 글

스프링 부트 계층 파악하기  (0) 2023.09.02
스프링 부트 구조  (1) 2023.09.02
스프링 부트 코드 이해 (1)  (0) 2023.08.31
스프링 부트 스타터  (0) 2023.08.31
스프링 Concept (2)  (0) 2023.08.31