본문 바로가기

Capstone-F5

SpringBoot Annotation 정리

스프링 부트 어노테이션 총정리

스프링 부트 어노테이션 총정리

1. 스프링 부트 어노테이션이란?

스프링 부트 어노테이션은 애플리케이션 개발에 필요한 설정을 간결하게 정의할 수 있다. 어노테이션을 활용하면 복잡한 XML 설정을 피할 수 있으며, 가독성과 유지보수성이 크게 향상된다.

2. 주요 스프링 부트 어노테이션

2.1 @Configuration

클래스가 하나 이상의 @Bean 메서드를 포함하며, 스프링 컨테이너에 빈(Bean)을 정의하는 데 사용.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}

2.2 @Bean

개발자가 직접 정의한 메서드를 빈으로 등록할 때 사용.

@Bean
public MyRepository myRepository() {
    return new MyRepository();
}

2.3 @Controller

Spring MVC에서 컨트롤러 클래스를 정의할 때 사용되며, HTTP 요청을 처리.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "index";
    }
}

2.4 @RestController

RESTful 웹 서비스를 제공할 때 사용되며, @Controller@ResponseBody를 합친 어노테이션이다.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {
    @GetMapping("/api/data")
    public String getData() {
        return "Hello from API!";
    }
}

2.5 @Component

스프링 컨테이너에서 관리할 클래스(빈)임을 나타낸다. @Service, @Repository는 이 어노테이션의 확장판이다.

@Component
public class MyComponent {
    public void execute() {
        System.out.println("Component executed");
    }
}

3. 추가적으로 알아두면 좋은 어노테이션

3.1 @RequestMapping

HTTP 요청의 URL과 메서드를 매핑. @GetMapping, @PostMapping 등 세분화된 어노테이션도 존재한다.

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping(value = "/user", method = RequestMethod.GET)
public String getUser() {
    return "User Data";
}

3.2 @Autowired

스프링 컨테이너에서 관리되는 빈을 자동으로 주입할 때 사용.

import org.springframework.beans.factory.annotation.Autowired;

@RestController
public class MyController {
    private final MyService myService;

    @Autowired
    public MyController(MyService myService) {
        this.myService = myService;
    }
}

3.3 @Qualifier

빈의 이름을 명시적으로 지정하여 주입할 때 사용. 동일한 타입의 여러 빈이 있을 경우 사용.

import org.springframework.beans.factory.annotation.Qualifier;

@Autowired
@Qualifier("specificService")
private MyService myService;

3.4 @Transactional

메서드 또는 클래스에 트랜잭션을 적용. 데이터베이스 작업에서 중요한 역할을 한다.

import org.springframework.transaction.annotation.Transactional;

@Transactional
public void updateData() {
    // 데이터베이스 업데이트 로직
}

3.5 @PathVariable

URL 경로에서 변수를 추출하여 매핑.

import org.springframework.web.bind.annotation.PathVariable;

@GetMapping("/user/{id}")
public String getUserById(@PathVariable("id") Long userId) {
    return "User ID: " + userId;
}

3.6 @RequestParam

쿼리 파라미터를 매핑.

import org.springframework.web.bind.annotation.RequestParam;

@GetMapping("/search")
public String search(@RequestParam("keyword") String keyword) {
    return "Search keyword: " + keyword;
}

4. 다양한 어노테이션 활용 예제

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class DemoController {

    private final UserService userService;

    @Autowired
    public DemoController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users/{id}")
    public String getUser(@PathVariable Long id) {
        return userService.findUserById(id);
    }

    @PostMapping("/users")
    public String createUser(@RequestParam String name, @RequestParam int age) {
        return userService.createUser(name, age);
    }
}

@Service
class UserService {
    public String findUserById(Long id) {
        return "User ID: " + id;
    }

    public String createUser(String name, int age) {
        return "Created user: " + name + ", age: " + age;
    }
}

5. 결론

스프링 부트 어노테이션은 코드의 효율성과 유지보수성을 극대화한다.

'Capstone-F5' 카테고리의 다른 글

SpringBoot 결제 로직  (0) 2024.12.02
AWS S3 사용을 통한 이미지 관리법  (0) 2024.12.02
CI/CD란?  (0) 2024.12.02
MSA 구조에서 서버간 통신 방법  (0) 2024.12.02
Docker 설치 방법 및 Swap 메모리 설정  (0) 2024.12.02