Spring에서 자주 사용되는 Annotation들을 MVC패턴에 따라 분류해보았다.
| Annotation | 설명 |
|---|---|
| @Entity | JPA 엔티티 클래스 지정 |
| @Table | 데이터베이스 테이블 매핑 |
| @Id | 기본키(PK) 필드 지정 |
| @GeneratedValue | PK 자동 생성 전략 지정 |
| @Column | 필드-컬럼 매핑, 이름 옵션 지정 |
| @Version | 낙관적 락(버전 관리) |
| @Transient | 매핑 제외 필드 |
| @PersistenceContext | EntityManager 주입 |
| @Autowired | 빈(Bean) 자동 주입 (주로 Repository, Service에서) |
예제 코드 (JPA 엔티티와 Repository):
import javax.persistence.*; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String username; // getter, setter } import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository { // 커스텀 메소드 추가 가능 }
@Autowired 활용 예제:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { private final UserRepository userRepository; @Autowired // 생성자 주입 public UserService(UserRepository userRepository) { this.userRepository = userRepository; } }
| Annotation | 설명 |
|---|---|
| (대표 Annotation 없음) | JSP, Thymeleaf 등 외부 템플릿 엔진을 통해 뷰 처리. |
| @ModelAttribute | (컨트롤러 파라미터 바인딩/뷰로 값 전달시 사용) |
View 계층에서는 Annotation의 비중이 낮으나, 모델 객체 전달 시
@ModelAttribute또는Model파라미터를 활용
| Annotation | 설명 |
|---|---|
| @Controller | 클래스를 웹 컨트롤러로 지정 |
| @RestController | REST API 컨트롤러, (JSON 등 응답) |
| @RequestMapping | URL/HTTP 메서드 매핑 |
| @GetMapping/… | HTTP 메서드별 매핑 |
| @RequestParam | 쿼리 파라미터 바인딩 |
| @PathVariable | URI 경로 변수 바인딩 |
| @RequestBody | HTTP 요청 BODY 바인딩 |
| @ResponseBody | 반환값을 HTTP 응답에 직접 매핑 |
| @ModelAttribute | 파라미터 및 모델 바인딩 |
| @SessionAttributes | 모델 속성을 세션에 저장 |
예제 코드:
import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { // User 객체 반환(JSON 자동 변환) return userService.findById(id); } @PostMapping public User createUser(@RequestBody User user) { // 요청 body의 JSON -> User 매핑 return userService.save(user); } }
| Annotation | 설명 |
|---|---|
| @Component | 스프링이 관리하는 일반 빈 등록 |
| @Service | 비즈니스 로직 클래스 명시 |
| @Repository | 데이터 접근 객체 명시 |
| @Configuration | 설정 클래스 지정 |
| @Bean | 개발자가 직접 빈 등록 |
| @ComponentScan | 컴포넌트 자동 탐색 범위 지정 |
| @Autowired | 빈 의존성 자동 주입 |
| @Value | 프로퍼티 값 주입 |
| @Transactional | 트랜잭션 적용 |
예제 코드 (설정 및 트랜잭션):
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; @Configuration public class AppConfig { @Bean public DataSource dataSource() { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setUrl("jdbc:h2:mem:testdb"); ds.setUsername("sa"); ds.setPassword(""); return ds; } }import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class OrderService { @Transactional public void processOrder(Long orderId) { // 이 메서드는 트랜잭션 내에서 동작함 } }