Создайте пользовательский RestControllerAnotation для выполнения requestMapping - PullRequest
0 голосов
/ 11 февраля 2020

Добрый день,

У меня есть 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 package 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 {
 }

Я знаю, что что-то упустил, но не вижу, что.

С уважением и большое спасибо!

1 Ответ

0 голосов
/ 11 февраля 2020

Вы можете использовать @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 -

...