【问题标题】:Create a custom RestControllerAnotation to execute a requestMapping创建自定义 RestControllerAnnotation 以执行 requestMapping
【发布时间】:2020-05-26 06:21:44
【问题描述】:

下午好,

我有一个restController,我想创建一个注释,允许或不执行基于自定义标头值的方法。 如果自定义标头标记等于某个值,则必须执行该方法,如果自定义标头不匹配,则该方法必须不执行 我关注了几篇文章,但我一直没能做到。

我附上了我创建的代码:

注释代码:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiVersion {
    int[] value();
}

ApiVersionRequestMappingHandlerMapping

    public class ApiVersionRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    private final String prefix;

    public ApiVersionRequestMappingHandlerMapping(String prefix) {
        this.prefix = prefix;
    }

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo info = super.getMappingForMethod(method, handlerType);
        if(info == null) return null;

        ApiVersion methodAnnotation = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        if(methodAnnotation != null) {
            RequestCondition<?> methodCondition = getCustomMethodCondition(method);
            // Concatenate our ApiVersion with the usual request mapping
            info = createApiVersionInfo(methodAnnotation, methodCondition).combine(info);
        } else {
            ApiVersion typeAnnotation = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
            if(typeAnnotation != null) {
                RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType);
                // Concatenate our ApiVersion with the usual request mapping
                info = createApiVersionInfo(typeAnnotation, typeCondition).combine(info);
            }
        }

        return info;
    }

    private RequestMappingInfo createApiVersionInfo(ApiVersion annotation, RequestCondition<?> customCondition) {
        int[] values = annotation.value();
        String[] patterns = new String[values.length];
        for(int i=0; i<values.length; i++) {
            // Build the URL prefix
            patterns[i] = prefix+values[i];
        }

        return new RequestMappingInfo(
                new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), useSuffixPatternMatch(), useTrailingSlashMatch(), getFileExtensions()),
                new RequestMethodsRequestCondition(),
                new ParamsRequestCondition(),
                new HeadersRequestCondition(),
                new ConsumesRequestCondition(),
                new ProducesRequestCondition(),
                customCondition);
    }

}

休息控制器

    @RestController
@RequiredArgsConstructor
@RequestMapping("/api/example")
public class ExampleController {

    private final UserService userService;

   @ApiVersion (1)
    @GetMapping("/myMethod")
   public String myMethod(@AuthenticationPrincipal UserAuthenticatedDetails userAuthenticated) {

      return userAuthenticated.getUsername();
    }
}

ApiConfig 包xx.package.sample;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@ComponentScan("xx.package")
@Configuration
@EnableTransactionManagement
@EntityScan("xx.package.domain.entity")
@EnableJpaRepositories("xx.package.domain.repository")
@EnableAutoConfiguration
public class ApiConfig {
 }

我知道我错过了什么,但我看不到什么。

问候,非常感谢!

【问题讨论】:

    标签: spring rest spring-boot annotations spring-restcontroller


    【解决方案1】:

    你可以使用@GetMapping(path = "/myMethod", headers = "My-Header=myValue")

    一系列“My-Header=myValue”样式表达式,带有一个请求 仅在发现每个此类标头具有给定值时才映射

    https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html#headers--

    【讨论】:

    • 早上好,我已经知道该解决方案并且它适合我的目标。我更喜欢知道如何创建一个注释来知道它是如何完成的。
    • 好吧,如果它不打扰你,我会为初学者提供答案,他们可能会在已经存在弹簧支持的情况下实施他们的注释来解决这个主题。但如果不受欢迎,我会删除它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多