Java 5+ Custom Annotation 사용법

David Jeon·2023년 5월 9일

Java & Spring

목록 보기
1/1
post-thumbnail

Java 5+ Custom Annotation 사용법

Custom Annotation은 자신만의 Annotation을 만들어서 사용할 수 있는 기능입니다. Annotation은 Java 언어의 메타데이터를 표현하는 방법입니다. 메소드, 클래스, 변수 등에 메타데이터를 추가하여 프로그램 실행 시 해당 메타데이터를 참조할 수 있습니다.
Spring Boot에서 Custom Annotation은 다양한 기능에 활용될 수 있습니다. 예를 들어, 특정 클래스나 메서드에 접근 권한을 부여하는 기능을 구현할 수 있습니다. 또는 Logging, Caching, Authentication, Authorization 등의 기능을 추가하기 위해 사용할 수도 있습니다.

Custom Annotation을 정의하려면 @interface 키워드를 사용합니다. 이 키워드를 사용하여 새로운 Annotation을 정의할 수 있습니다.

  • Custom Annotation을 선언하는 Interface
package sample;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
    int auth() default 5;
    String name();
}

위 예제는 @CustomAnnotation이라는 Custom Annotation을 정의하는 예시입니다. @Retention Annotation은 어느 시점까지 유지할 것인지를 정의하며, @Target Annotation은 어떤 대상에 적용할 수 있는지를 정의합니다.

설정할 수 있는 Meta Annotation은 다음과 같습니다.
@Target : 어노테이션의 적용 대상을 지정
@Documented : 어노테이션 정보를 javadoc 문서에 포함
@Inherited : 어노테이션이 하위 클래스에 상속 선언
@Retention : 어노테이션이 유지되는 기간 설정
@Repeatable : 어노테이션을 반복해서 적용

Custom Annotation을 적용하려면, 다음과 같이 사용할 수 있습니다.

  • Custom Annotation를 적용한 AuthInfo Class
package sample;

@CustomAnnotation(name = "David")
class AuthInfo {
}
  • AuthInfo 를 호출하는 Test Class
package sample;

import java.lang.annotation.Annotation;

public class AuthInfoTester {

    public static void main(String[] args) {
        AuthInfoTester authInfo = new AuthInfoTester();
        authInfo.print(new AuthInfo());
    }

    private void print(AuthInfo myInfo) {
        Annotation[] annotations = AuthInfo.class.getDeclaredAnnotations();

        for (Annotation i : annotations) {
            if (i instanceof CustomAnnotation) {
              CustomAnnotation customAnnotation = (CustomAnnotation) i;
              System.out.println("Name=[" + customAnnotation.name() + "], auth=[" + customAnnotation.auth() + "]");
            }
        }
    }
}

AuthInfoTester Class 실행 결과

-- End --

profile
코딩이 즐거운 아저씨

0개의 댓글