Post

[Spring] 어노테이션(Annotations)

📌 들어가며

스프링은 다양한 어노테이션으로 코드를 간결하게 만든다. 이번 글에서는 특히 웹 MVC빈 관리에서 자주 쓰이는 핵심 어노테이션을 정리한다.


1. 웹 MVC 어노테이션

어노테이션역할
@ControllerMVC 컨트롤러 정의
@RestController@Controller + @ResponseBody (JSON/XML 반환)
@RequestMappingURL ↔ 메소드 매핑
@RequestParam요청 파라미터 → 메소드 파라미터
@PathVariableURL 경로 일부 → 메소드 파라미터
@RequestBody요청 본문 → 자바 객체
@ResponseBody반환 객체 → 응답 본문
@ModelAttribute바인딩 객체를 모델에 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
@RequestMapping("/api")
public class MyController {

    @GetMapping("/user/{id}")           // URL 경로
    public User getUser(@PathVariable Long id) { ... }

    @GetMapping("/search")
    public String search(@RequestParam("q") String query) { ... }  // ?q=...

    @PostMapping("/user")
    public String addUser(@RequestBody User user) { ... }  // 본문 → 객체
}

💡 @RestController는 REST API의 표준이다. @Controller@ResponseBody를 매 메소드에 붙이는 대신, 클래스에 하나만 붙이면 된다.


2. 빈 등록·의존성 주입 어노테이션

어노테이션역할계층
@Component일반 빈 등록-
@Controller프레젠테이션 계층
@Service비즈니스 로직서비스
@Repository데이터 액세스DAO
@Autowired의존성 자동 주입-
@Configuration자바 기반 빈 설정-
@Transactional트랜잭션 관리-
1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class MyService {
    private final MyRepository myRepository;

    @Autowired   // 생성자 주입 (권장)
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    @Transactional   // 트랜잭션 범위 설정
    public void saveData(Data data) { myRepository.save(data); }
}

💡 @Controller·@Service·@Repository는 모두 @Component의 특수화로, 계층을 명확히 드러내는 역할도 한다.


📝 정리

1
2
3
4
5
6
Spring 어노테이션
├─ 매핑     @Controller/@RestController + @RequestMapping
├─ 파라미터  @RequestParam / @PathVariable / @RequestBody
├─ 빈 등록  @Component / @Service / @Repository
├─ 주입     @Autowired (생성자 권장)
└─ 기타     @Configuration, @Transactional
개념한 줄 정의
@RestControllerJSON 반환 컨트롤러
@Autowired의존성 자동 주입
@Service/@Repository계층별 빈 등록

스프링 어노테이션은 “무엇을 하는 클래스인지”를 선언적으로 드러낸다. 웹 MVC 매핑과 빈 등록·주입 어노테이션만 확실히 잡으면, 대부분의 스프링 애플리케이션을 읽고 쓸 수 있다.

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.