spring - 如何确保 Controller 在 Spring Boot 中被特定的注释所注释?

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

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

问题:

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

谢谢!

最佳答案

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

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

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

为此,您需要注册一个 ApplicationListener,它会搜索所有使用 @FeignClient 进一步注释的 @RequestMapping beans。

实现可能如下所示:

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

关于spring - 如何确保 Controller 在 Spring Boot 中被特定的注释所注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41093792/

相关文章:

java - spring-cloud-stream-kafka 配置 : instanceCount & instanceIndex

java - 我应该在我的 MVC 层和服务层中重复验证吗?

java - 基于时间和大小的记录器备份策略

java - 即使该类可用,也会出现 ClassNotFoundException

java - 从属性/XML 文件中设置 web.xml 中的上下文参数

java - 当我有很多 SpringBootTest 类时,如何有效地使用嵌套配置类来注入(inject)依赖项

java.lang.AssertionError : Content type not set

java - Mongodb 聚合(Java/Spring)查询以获取最后一个子元素

java - 使用 Spring MVC 上传文件不起作用

java - 无法使用 Spring 执行器 - 创建 bean CacheMetricsRegistrarConfiguration 时出错