Java Spring 어노테이션 자세한 설명
Spring 프레임워크는 Java 애플리케이션 개발에서 널리 사용되는 프레임워크이며, 다양한 어노테이션(Annotations)을 제공하여 개발자가 효율적으로 코드를 작성할 수 있도록 돕습니다. 스프링 어노테이션은 XML 기반 설정을 줄이고, 코드의 가독성과 유지보수성을 높이는 데 중요한 역할을 합니다.
이 글에서는 스프링에서 사용되는 주요 어노테이션을 기본 어노테이션, 의존성 주입 관련 어노테이션, Spring MVC 어노테이션, AOP 관련 어노테이션, 트랜잭션 관련 어노테이션 등의 카테고리로 나누어 자세히 살펴보겠습니다.
1. 기본 어노테이션
1.1 @Configuration
- 클래스가 하나 이상의 빈(Bean)을 정의하고 있으며, 스프링 컨테이너가 이를 관리하도록 지정할 때 사용합니다.
- @Bean 어노테이션과 함께 사용됩니다.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
1.2 @Component
- 스프링이 자동으로 빈(Bean)으로 등록할 클래스를 나타냅니다.
- @ComponentScan과 함께 사용하면 특정 패키지를 검색하여 @Component가 붙은 클래스를 빈으로 등록할 수 있습니다.
@Component
public class MyComponent {
public void doSomething() {
System.out.println("Hello, Component!");
}
}
1.3 @ComponentScan
- 특정 패키지를 스캔하여 @Component가 붙은 클래스를 자동으로 빈으로 등록합니다.
@Configuration
@ComponentScan(basePackages = "com.example.service")
public class AppConfig {
}
2. 의존성 주입 관련 어노테이션
2.1 @Autowired
- 스프링의 자동 의존성 주입을 수행하는 어노테이션입니다.
- 생성자, 필드, 메서드에 사용할 수 있습니다.
@Component
public class MyService {
public void serve() {
System.out.println("Service Running...");
}
}
@Component
public class MyController {
@Autowired
private MyService myService;
public void process() {
myService.serve();
}
}
2.2 @Qualifier
- @Autowired가 여러 개의 빈을 찾을 때 특정 빈을 지정하는 어노테이션입니다.
@Component("serviceA")
public class ServiceA implements MyService {
}
@Component("serviceB")
public class ServiceB implements MyService {
}
@Component
public class MyController {
@Autowired
@Qualifier("serviceA")
private MyService myService;
}
2.3 @Primary
- 같은 타입의 빈이 여러 개일 때 우선순위가 높은 빈을 지정합니다.
@Component
@Primary
public class DefaultService implements MyService {
}
2.4 @Value
- 속성 값을 주입할 때 사용합니다.
@Value("${app.name}")
private String appName;
3. Spring MVC 어노테이션
3.1 @Controller
- 스프링 MVC에서 컨트롤러 역할을 하는 클래스를 지정합니다.
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
3.2 @RestController
- @Controller + @ResponseBody를 포함하는 어노테이션입니다.
- REST API를 만들 때 사용합니다.
@RestController
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
3.3 @RequestMapping
- 요청 URL을 매핑할 때 사용합니다.
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable String id) {
return "User ID: " + id;
}
}
3.4 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping
- HTTP 메서드별 요청을 처리합니다.
@RestController
@RequestMapping("/items")
public class ItemController {
@PostMapping
public String createItem() {
return "Item Created";
}
}
3.5 @RequestBody
- 요청 본문을 객체로 변환합니다.
@PostMapping("/create")
public ResponseEntity<String> create(@RequestBody User user) {
return ResponseEntity.ok("User Created: " + user.getName());
}
3.6 @ResponseBody
- 반환값을 HTTP 응답 본문으로 변환합니다.
@GetMapping("/json")
@ResponseBody
public User getUser() {
return new User("John", 25);
}
4. AOP 관련 어노테이션
4.1 @Aspect
- AOP(관점 지향 프로그래밍)에서 관점(Aspect)을 정의하는 클래스에 붙입니다.
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Method Called: " + joinPoint.getSignature());
}
}
4.2 @Before, @After, @Around
- AOP에서 특정 시점에 메서드를 실행하도록 합니다.
@Around("execution(* com.example.service.*.*(..))")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
System.out.println("Execution Time: " + executionTime + "ms");
return result;
}
5. 트랜잭션 관련 어노테이션
5.1 @Transactional
- 데이터베이스 트랜잭션을 관리할 때 사용합니다.
@Service
public class UserService {
@Transactional
public void createUser(User user) {
userRepository.save(user);
// 예외 발생 시 롤백됨
}
}
5.2 @Rollback
- 테스트에서 트랜잭션 롤백을 설정할 때 사용합니다.
@Test
@Rollback
public void testCreateUser() {
userService.createUser(new User("John"));
}
6. 스프링 부트 추가 어노테이션
6.1 @SpringBootApplication
- 스프링 부트의 부트스트랩 클래스를 지정합니다.
- @Configuration, @EnableAutoConfiguration, @ComponentScan을 포함합니다.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
6.2 @EnableScheduling
- 스프링에서 스케줄링을 활성화할 때 사용합니다.
@EnableScheduling
@Configuration
public class SchedulerConfig {
}
'게으른 개발자의 끄적거림' 카테고리의 다른 글
RPA 주요 Activity(기능) 완벽 정리 (0) | 2025.03.17 |
---|---|
Spring @Component @Bean 완벽 정리 (0) | 2025.03.15 |
리액트(react.js) 기본 문법 완벽 정리 (0) | 2025.03.11 |
SQL의 이해 (SQL의 기본에 대해서) (0) | 2025.03.10 |
어플리케이션(Application)이란? (0) | 2025.03.08 |