Search code examples
springspring-mvcspring-bootannotationsnetflix-feign

How to make sure a controller is annotated by a specific annotation in spring boot?


@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!


Solution

  • I suspect that you are having trouble related to this issue https://github.com/spring-cloud/spring-cloud-netflix/issues/466.

    The spring applicationContext offers utility methods for looking up beans with certain annotations present.

    The solution could involve bootstrapping the start of the applicationContext and searching for your overlapping annotations there.

    For this to work your need to register an ApplicationListener which searches all of your @RequestMapping beans which are further annotated with @FeignClient.

    The implementation might look like :

    @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);
                }
            }
        }
    }