728x90
반응형
1. 개요
Spring 프레임워크는 다양한 어노테이션을 제공하여 개발자가 더욱 직관적이고 간결하게 애플리케이션을 개발할 수 있도록 지원합니다. 이번 글에서는 Spring에서 자주 사용되는 핵심 어노테이션들을 정리하고, 각 어노테이션의 역할과 사용 방법을 살펴보겠습니다.

2. 주요 어노테이션 정리
2.1. 컴포넌트 스캔 관련 어노테이션
@Component
- 스프링이 관리하는 일반적인 빈(Bean)으로 등록할 때 사용됩니다.
- 예제
@Component
public class MyComponent {
public void doSomething() {
System.out.println("Hello, Component!");
}
}
@Controller, @Service, @Repository
- 역할에 따라 클래스를 분류하는 어노테이션으로, 내부적으로 @Component를 포함하고 있습니다.
- 예제
@Service
public class MyService {
public String getMessage() {
return "Hello, Service!";
}
}
2.2. 의존성 주입 관련 어노테이션
@Autowired
- 자동으로 빈을 주입할 때 사용됩니다.
- 예제
@Component
public class MyComponent {
private final MyService myService;
@Autowired
public MyComponent(MyService myService) {
this.myService = myService;
}
}
@Qualifier
- 같은 타입의 여러 개의 빈이 있을 때 특정한 빈을 선택하여 주입할 수 있도록 합니다.
- 예제
@Component("beanA")
public class BeanA {}
@Component("beanB")
public class BeanB {}
@Component
public class MyComponent {
private final BeanA beanA;
@Autowired
public MyComponent(@Qualifier("beanA") BeanA beanA) {
this.beanA = beanA;
}
}
반응형
728x90
2.3. AOP 관련 어노테이션
@Aspect
- AOP(Aspect-Oriented Programming)에서 사용되며, 공통 기능(예: 로깅, 트랜잭션 관리 등)을 적용할 수 있습니다.
- 예제:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethodExecution() {
System.out.println("메서드 실행 전 로그");
}
}
2.4. 트랜잭션 관리 어노테이션
@Transactional
- 트랜잭션을 자동으로 관리하도록 도와줍니다.
- 예제
@Service
public class AccountService {
@Transactional
public void transferMoney(Long fromAccountId, Long toAccountId, Double amount) {
// 계좌 이체 로직
}
}
2.5. 설정 관련 어노테이션
@Configuration
- 스프링 설정 클래스를 정의할 때 사용합니다.
- 예제:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Bean
- 수동으로 빈을 등록할 때 사용됩니다.
2.6. 요청 처리 관련 어노테이션
@RequestMapping
- 특정 URL 요청을 처리하는 메서드를 정의할 때 사용됩니다.
- 예제:
@RestController
public class MyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "Hello, Spring!";
}
}
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping
- HTTP 메서드에 맞춰 사용되는 축약형 어노테이션입니다.
- 예제:
@RestController
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring!";
}
}
728x90
반응형
'공부 > SpringFramework' 카테고리의 다른 글
[SpringBoot] Spring Boot Thymeleaf 설정 (0) | 2023.12.14 |
---|---|
[SpringBoot] 스프링부트를 사용해서 웹 서버 기본 틀 만들기 (1) | 2021.04.21 |