Dominic
Dominic

Reputation: 129

Http Header Field in @Bean Method

I am using spring boot version 2.0.5. I have a @Bean method to create request scopes beans but to create the instance I need to access the http header fields of the request I create the instance for. The @RequestHeader annotation works fine in my @RestController but not in my @Bean method. Does anyone know how to access that information in that context?

Below is an example of what I would like to do but as it does not work as the @RequestHeader annotation does not work in that contest.

Thank you for any hint.

Best regards, Dominic

@Configuration
public class AProducer {

@Bean
@Scope(value="request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public User produceUser( @RequestHeader(value="Accept") String acceptType ) {
    ....
    }

}

Upvotes: 2

Views: 3690

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40048

@RequestHeader annotations is only supported on handler methods, from docs here

public @interface RequestHeader

Annotation which indicates that a method parameter should be bound to a web request header. Supported for annotated handler methods in Spring MVC and Spring WebFlux.

If the method parameter is Map, MultiValueMap, or HttpHeaders then the map is populated with all header names and values.

So get the Header values in web request handler method in Controller class and pass it through the method arguments to produceUser

Example: This is the method in Controller Class which is annotated with either @Controller or @RestController

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                          @RequestHeader("Keep-Alive") long keepAlive)  {
         //call the `produceUser(String reqParam)` method by autowiring `AProducer` class
}

or simply you can try private @Autowired HttpServletRequest request; in AProducer class and get headers as suggested by @JB Nizet;

@Configuration
public class AProducer {

  private @Autowired HttpServletRequest request

 @Bean
 @Scope(value="request", proxyMode = ScopedProxyMode.TARGET_CLASS)
 public User produceUser( @RequestHeader(value="Accept") String acceptType ) {
....      //String value =request.getHeader("Accept")
     }

 }

Upvotes: 5

Related Questions