2

@FeignClient and @RequestMapping could not be added to the same interface. Now I want to check whether the two annotations were used an the same time to give some error messages.

Question:

Is there a something like isAnnotatedBy(Annotation annotation) method supported in spring? If not, how could I achieve my goal here?

Thanks!

4

2 回答 2

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);
            }
        }
    }
}
于 2016-12-12T18:16:55.693 回答
0

已经有支持的方法名为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
于 2016-12-12T07:48:23.263 回答