【问题标题】:How to make sure a controller is annotated by a specific annotation in spring boot?如何确保控制器在 Spring Boot 中被特定注释注释?
【发布时间】:2016-12-12 03:28:45
【问题描述】:

@FeignClient@RequestMapping 无法添加到同一界面。现在我想检查两个注释是否同时使用以给出一些错误消息。

问题:

spring 支持类似isAnnotatedBy(Annotation annotation) 的方法吗?如果没有,我怎么能在这里实现我的目标?

谢谢!

【问题讨论】:

    标签: spring spring-mvc spring-boot annotations netflix-feign


    【解决方案1】:

    我怀疑您遇到了与此问题相关的问题https://github.com/spring-cloud/spring-cloud-netflix/issues/466

    spring applicationContext 提供了一些实用方法来查找带有某些注解的bean。

    解决方案可能涉及引导 applicationContext 的开始并在那里搜索您的重叠注释。

    为此,您需要注册一个 ApplicationListener 来搜索您的所有 @RequestMapping bean,这些 bean 进一步使用 @FeignClient 进行注释。

    实现可能如下所示:

    @Component
    public class ContextStartupListener
            implements ApplicationListener<ContextRefreshedEvent> {
    
        @Autowired    
        private ApplicationContext applicationContext;
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event){
        for(String beanName : applicationContext.getBeanNamesForAnnotation(RequestMapping.class)) {
               if(applicationContext.findAnnotationOnBean(beanName, FeignClient.class)!=null){
                    throw new AnnotationConfigurationException("Cannot have both @RequestMapping and @FeignClient on "+beanName);
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      已经有一个名为isAnnotationPresent的支持方法:

      boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
      Returns true if an annotation for the specified type is present on this element, else false. This method is designed primarily for convenient access to marker annotations.
      Parameters:
      annotationClass - the Class object corresponding to the annotation type
      Returns:
      true if an annotation for the specified annotation type is present on this element, else false
      Throws:
      NullPointerException - if the given annotation class is null
      Since:
      1.5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        • 2019-02-22
        • 2020-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-27
        相关资源
        最近更新 更多