Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
¿Hay alguna opción para agregar un valor predeterminado a todos los @RequestHeaders en Spring Boot?

¿Hay alguna opción para agregar un valor predeterminado a todos los @RequestHeader en el arranque de primavera?

@RequestHeader(value = "User-Accept-Language", defaultValue = "en-IN") String localeCd

Estoy copiando/pegando todas las API. ¡Alguna ayuda para evitar la duplicación de código!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

No encontré nada ya hecho para tener una anotación para agregar un encabezado con un valor, así que hice el mío. Aquí está el código, es muy simple, lo hice usando Spring AOP

  1. Creé las clases de anotación.

     import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ResponseHeader { public String key() default ""; public String value() default ""; }

    y el que contiene una matriz de anotaciones de encabezados

     import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ResponseHeaders { public ResponseHeader[] headers(); }
  2. La clase AOP para capturar los restControllers (puede personalizar el AOP para configurar su propio punto de corte como desee:

     import YOUR_PACKAGE_ANNOTATION.ResponseHeaders; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * Aspect for inserting headers on the methods of the @RestController annotated classes */ @Aspect @Component public class ResponseHeadersAnnotation { /** * Pointcut for filtering just classes with @RestController annotation */ @Pointcut("@within(org.springframework.web.bind.annotation.RestController)") public void restControllerClass() { } /** * It adds the headers to the response of the method of the controller * * @param responseHeaders */ @After("restControllerClass() && @annotation(responseHeaders)") public void addHeaders(final ResponseHeaders responseHeaders) { final HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); List.of(responseHeaders.headers()).forEach(responseHeader -> response.setHeader(responseHeader.key(), responseHeader.value())); } }
  3. Aquí hay un ejemplo de cómo usarlo en un controlador:

     @GetMapping(value = {"/ServiceTicketCollection", "/ServiceRequestCollection"}) @ResponseHeaders(headers = { @ResponseHeader(key = "cookie1", value = "value1"), @ResponseHeader(key = "cookie2, value = "value2") }) public Object restControllerMethod() { ... }
over 4 years ago · Santiago Trujillo Report

0

Este es un ejemplo de cómo proporcionar un valor predeterminado para un encabezado usando Spring WebFlux

 @Component public class CorrelationIdFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { var correlationId = exchange.getRequest().getHeaders().getFirst(CORRELATION_ID_HEADER); if (correlationId == null || correlationId.isEmpty()) { correlationId = UUID.randomUUID().toString(); ServerHttpRequest mutatedRequest = exchange.getRequest() .mutate() .header(CORRELATION_ID_HEADER, correlationId) .build(); exchange = exchange .mutate() .request(mutatedRequest) .build(); } exchange.getResponse().getHeaders().add(CORRELATION_ID_HEADER, correlationId); return chain.filter(exchange); } }

Y esto es para Spring web

 @Component public class CorrelationIdFilter implements Filter { static final String CORRELATION_ID_HEADER = "X-Correlation-ID"; @Override public void init(FilterConfig filterConfig) { // empty } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String correlationId = httpRequest.getHeader(CORRELATION_ID_HEADER); if (correlationId == null) { correlationId = XidFactory.nextXid(); ((HttpServletResponse) response).addHeader(CORRELATION_ID_HEADER, correlationId); } chain.doFilter(request, response); } @Override public void destroy() { // empty } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!