Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

匿名接口注解——匿名注解解析方式优化 #239

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

LeoTan2004
Copy link

SpringAOP获取注解的方式

RequestMapping base = AnnotationUtils.getAnnotation(beanClass, RequestMapping.class);

这种方式能不仅能够获取直接使用在这个类上面的注解,也可以获取该类上的注解的元注解。
我们以RequestMappingPostMapping为例(简化后)

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
	String[] value() default {};
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {
    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};
}

测试用例

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;


@PostMapping("test")
class PostController{

}

public class Test{
    public static void main(String[] args) {
        RequestMapping base = 
            AnnotationUtils.getAnnotation(PostController.class, RequestMapping.class);
        // 这里不仅base不会为空,而且PostMapping中的值还会传递给RequestMapping
        System.out.println(base.value());
    }
}

@LeoTan2004
Copy link
Author

使用SpringAOP提供的方式获取注解,就相当于注解获得了继承和多态的特性,这也给之后的扩展提供了更大的空间。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant