Spring@RestController 주해 조합 실현 방법 분석

Spring 에는@RestController 와 같은 주석 조합 이 많이 존재 합 니 다.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";

}
@RestController 는@Controller,@ResponseBody 두 주해 의 조합 으로 두 주해 의 역할 을 동시에 합 니 다.
저 는 처음에 이것 이 자바 의 특성 이 라 고 생각 했 습 니 다.자바 는 주해 상의 주 해 를 통 해 자동 조합 주 해 를 실현 할 수 있 습 니 다.그래서 이런 코드 를 썼어 요.

/**
 * @author Fcb
 * @date 2020/6/23
 * @description
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyComponent {
}

/**
 * @author Fcb
 * @date 2020/6/23
 * @description
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@MyComponent
public @interface MyController {
}

@MyController
public class AnnotatedService {
}
결과 테스트 결과 전복 되 었 습 니 다.

/**
 * @author Fcb
 * @date 2020/6/23
 * @description
 */
public class Test {

  public static void main(String[] args) {
    Annotation[] annotations = AnnotatedService.class.getAnnotations();
    for (Annotation anno : annotations) {
      System.out.println(anno.annotationType());
      System.out.println(anno.annotationType() == MyComponent.class);
    }
  }
}
인쇄 결 과 는 다음 과 같 습 니 다.
interface com.example.demo.anno.MyController
false
본인 이 자 료 를 찾 아 본 결과 제 가 원 하 는 주해 조합 주해 의 기능 은 Spring 이 스스로 실현 한 것 입 니 다.Spring 의 AnnotationUtils.find Annotation(클래스,주해)방법 을 통 해 특정한 클래스 에서 조합의 주 해 를 찾 을 수 있 는 지 여 부 를 판단 합 니 다.
예 를 들 어 지금 저 는 Annotated Service 라 는 종류 에@MyComponent 주해 가 존재 하 는 지 알 고 싶 습 니 다.이것 은 제 가 처음에 목적(조합 을 통 해 주 해 를 줄 이 는 것)이 었 기 때문에 코드 를 호출 할 수 있 습 니 다.

/**
 * @author Fcb
 * @date 2020/6/23
 * @description
 */
public class Test {

  public static void main(String[] args) {
    Annotation[] annotations = AnnotatedService.class.getAnnotations();
    System.out.println(AnnotationUtils.findAnnotation(AnnotatedService.class, MyComponent.class));
  }
}
인쇄 는 다음 과 같 습 니 다:
@com.example.demo.anno.MyComponent()
들 어 오 는 주석 이 존재 하지 않 는 값 이 라면 null 로 돌아 갑 니 다.예 는 다음 과 같 습 니 다.

/**
 * @author Fcb
 * @date 2020/6/23
 * @description
 */
public class Test {

  public static void main(String[] args) {
    Annotation[] annotations = AnnotatedService.class.getAnnotations();
    System.out.println(AnnotationUtils.findAnnotation(AnnotatedService.class, OtherAnno.class));
  }
}
콘 솔 인쇄:
null
요약:자바 자체 가 주 해 를 표시 하여 주 해 를 조합 하 는 기능 을 실현 하지 못 했 습 니 다.만약 우리 가 주 해 를 사용자 정의 할 때 Spring 의 AnnotationUtils.find Annotation()방법 을 사용 하여 우리 가 실현 할 수 있 도록 도와 줄 수 있다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기