728x90
1. @Transactional
메소드나 클래스 단위로 트랜잭션을 적용하는 어노테이션
- 해당 메소드가 정상적으로 완료되면 커밋되고,
- 예외(Exception)가 발생하면 자동으로 롤백(Rollback)
- 주로 DB를 다루는 서비스 계층에 붙여 사용
- 기본적으로 RuntimeException 또는 Error가 발생할 때만 롤백(SQLException 같은 체크 예외는 별도로 설정해야 롤백)
테스트 케이스에 이 어노테이션이 있으면 테스트 시작 전에 트랜잭션을 시작하고, 테스트 완료 후에 항상 롤백한다. 이렇게 하면 DB에 데이터가 남지 않으므로 다음 테스트에 영향을 주지 않는다.
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
@Transactional
public void processPayment() {
// 결제 처리 로직
// 중간에 예외가 발생하면 모든 작업이 롤백
}
}
- 클래스에 붙이면 클래스 내부의 모든 public 메소드에 적용
- 트랜잭션 전파(Propagation), 격리 수준(Isolation) 같은 옵션도 설정할 수 있음
@Transactional(readOnly = true)
public void findData() {
// 데이터 조회용 트랜잭션 (쓰기 금지)
}
2. @Configuration
Spring 설정 클래스를 정의하는 어노테이션
- 이 어노테이션이 붙은 클래스는 스프링 컨테이너가 직접 관리하는 설정 파일처럼 동작
- 개발자가 직접 Bean을 등록하거나, 환경 설정을 할 수 있음
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
3. @Bean
개발자가 직접 스프링 컨테이너에 등록하고 싶은 객체를 등록할 때 사용하는 어노테이션
- @Bean이 붙은 메서드는 실행 결과로 반환하는 객체를 Spring 빈으로 등록합니다.
- 주로 라이브러리 객체, 직접 생성한 객체, 또는 설정이 필요한 객체를 등록할 때 사용합니다.
- 스프링이 관리하지 않는 외부 라이브러리(ex: 외부 API Client 등)를 연결할 때 유용합니다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public ExternalService externalService() {
return new ExternalService("API-KEY-1234");
}
}
- @Component는 클래스에 붙이는 반면, @Bean은 메서드에 붙인다.
- 메서드 이름이 빈 이름(bean name) 이 된다.
4. @Component
스프링 컨테이너가 관리하는 객체(Bean)를 등록하는 어노테이션
- 별다른 설정 없이 클래스를 빈으로 등록할 수 있음
- 주로 핵심 로직이 담긴 클래스나 유틸리티 클래스에 사용
- @Service, @Repository, @Controller는 @Component를 확장한 스테레오타입
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
public String hello() {
return "Hello, Component!";
}
}
5. @Controller
웹 요청을 받아 처리하는 컨트롤러 클래스임을 명시하는 어노테이션
- 주로 View 페이지를 반환 (ex: Thymeleaf, JSP)
- 요청 URL을 메서드와 매핑해 처리
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Controller!");
return "hello"; // templates/hello.html 렌더링
}
}
6. @RestController
@Controller에 @ResponseBody 기능이 추가된 어노테이션
- View가 아닌 데이터(JSON, XML 등) 를 바로 반환
- 주로 REST API 서버를 만들 때 사용
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyRestController {
@GetMapping("/api/hello")
public String hello() {
return "Hello, API!";
}
}
7. @Service
비즈니스 로직을 수행하는 서비스 계층 클래스에 붙이는 어노테이션
- 의미적으로 "이 클래스는 비즈니스 로직을 담당합니다" 를 명확히 표현
- 코드 가독성과 유지보수성을 높임
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String process() {
return "Processing Service Logic...";
}
}
8. @Repository
데이터베이스 접근을 담당하는 DAO 클래스에 붙이는 어노테이션
- 데이터베이스 예외를 스프링이 감싸서 (DataAccessException) 던질 수 있게 지원
import org.springframework.stereotype.Repository;
@Repository
public class MyRepository {
public String findData() {
return "Data from DB";
}
}
9. @Autowired
스프링 컨테이너에 등록된 Bean을 자동으로 주입할 때 사용하는 어노테이션
- 생성자, 필드, 세터 메서드 등에 붙일 수 있음
- 생성자가 1개만 있을 경우 생략 가능
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final MyRepository myRepository;
@Autowired
public OrderService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
10. @RequestMapping
요청에 대한 URL을 매핑하는 어노테이션
- 클래스나 메서드 단위로 사용해 URL을 매핑할 수 있음
- 아무 것도 지정하지 않으면 모든 HTTP 메서드(GET, POST 등) 요청을 받는다.
- method 속성을 설정하면, 특정 HTTP 메서드 요청만 처리할 수 있다.
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/greet")
public class GreetingController {
// 아무것도 지정하지 않으면 모든 요청(GET, POST 등)을 받는다
@RequestMapping
public String greet() {
return "Hello!";
}
// GET 요청만 처리하도록 지정
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String hi() {
return "Hi!";
}
}
- @RequestMapping("/url") → 모든 요청(GET, POST 등) 처리
- @RequestMapping(value = "/url", method = RequestMethod.GET) → 특정 메서드(GET)만 처리
11. @GetMapping, @PostMapping 등
HTTP 메서드에 특화된 @RequestMapping의 축약형
- 가독성을 높이기 위해 GET, POST, PUT, DELETE 각각 전용 어노테이션을 제공
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable Long id) {
return "User " + id;
}
@PostMapping
public String createUser() {
return "User Created!";
}
}
12. @PathVariable
URL 경로의 일부를 변수로 받아올 때 사용하는 어노테이션
- URL 경로를 통해 전달된 값을 메서드의 파라미터로 받을 수 있음
@GetMapping("/item/{itemId}")
public String getItem(@PathVariable String itemId) {
return "Item ID: " + itemId;
}
13. @RequestParam
요청 파라미터(쿼리 스트링)를 받아올 때 사용하는 어노테이션
- ex) /search?keyword=Spring 형태에서 keyword 값을 추출
@GetMapping("/search")
public String search(@RequestParam String keyword) {
return "Searching for: " + keyword;
}
14. @Transactional
트랜잭션 처리를 적용할 때 사용하는 어노테이션
- 메소드나 클래스에 적용 가능
- 에러 발생 시 자동으로 rollback 처리
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
@Transactional
public void pay() {
// 결제 로직
// 에러 발생 시 자동으로 롤백됨
}
}
어노테이션 역할 정리
@Component, @Service, @Repository, @Controller | 스프링 Bean 등록 |
@Autowired | 스프링 Bean 주입 |
@RequestMapping, @GetMapping, @PostMapping | URL과 메서드 매핑 |
@PathVariable, @RequestParam | 요청 데이터 매핑 |
@RestController | API용 데이터 반환 컨트롤러 |
@Transactional | 트랜잭션 적용 (DB 작업의 원자성 보장) |
@Configuration, @Bean | 스프링 설정 및 수동 빈 등록 |
728x90
'Backend > Spring Boot' 카테고리의 다른 글
[Spring] ResponseEntity란? (0) | 2022.11.30 |
---|