Spring Annotation

임유진·2025년 8월 7일

목록 보기
7/7
post-thumbnail

Spring에서 자주 사용되는 Annotation들을 MVC패턴에 따라 분류해보았다.

M (Model, Repository)

Annotation설명
@EntityJPA 엔티티 클래스 지정
@Table데이터베이스 테이블 매핑
@Id기본키(PK) 필드 지정
@GeneratedValuePK 자동 생성 전략 지정
@Column필드-컬럼 매핑, 이름 옵션 지정
@Version낙관적 락(버전 관리)
@Transient매핑 제외 필드
@PersistenceContextEntityManager 주입
@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;
    }
}

V (View)

Annotation설명
(대표 Annotation 없음)JSP, Thymeleaf 등 외부 템플릿 엔진을 통해 뷰 처리.
@ModelAttribute(컨트롤러 파라미터 바인딩/뷰로 값 전달시 사용)

View 계층에서는 Annotation의 비중이 낮으나, 모델 객체 전달 시 @ModelAttribute 또는 Model 파라미터를 활용


C (Controller)

Annotation설명
@Controller클래스를 웹 컨트롤러로 지정
@RestControllerREST API 컨트롤러, (JSON 등 응답)
@RequestMappingURL/HTTP 메서드 매핑
@GetMapping/…HTTP 메서드별 매핑
@RequestParam쿼리 파라미터 바인딩
@PathVariableURI 경로 변수 바인딩
@RequestBodyHTTP 요청 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) {
        // 이 메서드는 트랜잭션 내에서 동작함
    }
}
profile
말하는 고구마

0개의 댓글