엄지월드

RequestMapping Annotation 구현 본문

java/Spring

RequestMapping Annotation 구현

킨글 2022. 12. 18. 18:04
반응형

리플렉션을 활용하여 간단하게 RequestMapping을 구현해보아야겠다.

 

Annotation 생성 코드

- @Target(value = ElementType.METHOD)를 통해서 메소드 위에 사용할 Annotation임을 명시해준다.

- @Retention(RetentionPloicy.RUNTIME)을 통해서 해당 어노테이션의 생명 주기를 지정해 준다.
여기서는 RUNTIME 으로 썻기 때문에 런타임 시에까지 계속 지정이 된다. 

package Custom;

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

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RQ {
    String url();
}

 

메소드 위에 Annotation을 선언해준다.

package Custom;

public class People {
    @RQ(url = "test")
    public void method1(){
        System.out.println("test");
    }

    @RQ(url = "add")
    public void method2(){
        System.out.println("add");
    }
}

 

선언한 Annotation을 호출하기 위해서 리플렉션을 활용해서 Annotation이 있는지 확인하고, 있으면 RQ.url()을 호출해서 값을 가져온다.

package Custom;

import java.lang.reflect.Method;

public class test {
    public static void main(String[] args) throws ClassNotFoundException {
        test t = new test();
        t.solution();
    }
    public void solution() throws ClassNotFoundException {
        // People Class의 정보를 읽어오기 위해 forName에 위치를 지정해준다.
        Class<?> cls = Class.forName("Custom.People");
        // 해당 클래스에 있는 메소드 목록을 가져온다.
        Method[] methods = cls.getDeclaredMethods();
        for(Method method : methods){
            // 만약 RQ 어노테이션이 존재하면
            if(method.isAnnotationPresent(RQ.class)){
                RQ rq = method.getAnnotation(RQ.class);
                // RQ로 선언한 url 값을 가져온다.
                System.out.println(rq.url() +" "+method.getName());
            }
        }
    }
}

 

실행된 화면 

System.out.println(rq.url() +" "+method.getName());

Comments