1. 어노테이션을 사용하는 이유는 무엇일까?
2. 나만의 어노테이션은 어떻게 만들 수 있을까?
"데이터를 설명하는 데이터"
예시
- 데이터 : 자바의 정석
- 메타데이터 : 저자: 남궁성, 출판년도: 2016
import org.springframework.stereotype.Component;
@Component //스프링이 자동 관리 (빈으로 클래스 등록)
public class MyComponent {
public void doSomething() {
System.out.println("컴포넌트 실행 중!");
}
}
유사 어노테이션
@Component
class Engine {
public void start() {
System.out.println("엔진이 가동됩니다!");
}
}
@Component
class Car {
@Autowired // Engine 객체를 자동으로 주입
private Engine engine;
public void drive() {
engine.start();
System.out.println("차가 출발합니다!");
}
}
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/hello") // 기본 URL 패턴 설정
public class HelloController {
@GetMapping // GET 요청을 처리
public String sayHello() {
return "안녕하세요!";
}
@PostMapping // POST 요청을 처리
public String postHello() {
return "POST 요청 완료!";
}
}
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MyService {
@Transactional // 트랜잭션을 자동으로 관리
public void processData() {
// DB 작업 수행
System.out.println("데이터 처리 중...");
}
}
<XML 설정 방식>
<bean id="myComponent" class="com.example.MyComponent"/>
<어노테이션 활용>
@Component
public class MyComponent { }
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) // 실행 시에도 유지됨
@Target(ElementType.METHOD) // 메서드에 적용 가능
public @interface LogExecutionTime { }
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
@Component
public class LogAspect {
@Around("@annotation(LogExecutionTime)") // LogExecutionTime이 붙은 메서드를 감싸서 실행
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long end = System.currentTimeMillis();
System.out.println("메서드 실행 시간: " + (end - start) + "ms");
return result;
}
}
import org.springframework.stereotype.Service;
@Service
public class MyService {
@LogExecutionTime
public void doWork() {
System.out.println("작업 수행 중...");
}
}