6

Spring MVC controller methods accespt different parameters that are injected before the method is invoked. Like HttpServletRequest, HttpServletResponse, java.security.Principal, etc.

@RequestMapping("/test")
public String test(HttpServletRequest req, Principal user){}

How can I declare something that can be injected in a controlelr method?

@RequestMapping("/test")
public String test(MyCustomInjectable myInjectable){}

More on the specific case:

I want to parse the HttpServletRequest in some servlet filter and construct an object that will be used in the controller method. More precisely I will parse a JWT token and access the claims.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
  • If it is the same request object, you could set each field value in request as request attribute, spring will automatically create your custom object based on the request attribute names. If you need custom object later in other requests you could get a session from request and save custom object in the sesssion with session attribute – Pragnani Aug 03 '16 at 10:59
  • Maybe related: https://stackoverflow.com/questions/17741787/injecting-custom-principal-to-controllers-by-spring-security – ch271828n Jul 01 '20 at 03:12

1 Answers1

4

There is an option to create custom HandlerMethodArgumentResolver.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
  • Exactly what i was looking for. Thanks. – Evgeni Dimitrov Aug 03 '16 at 11:19
  • If one uses this, can one inject a prototype bean that is configured with a factory method that has an `InjectionPoint` parameter, and in this way inject a customized bean that depends on the other parameters of the controller method (for example, path variables) ? – herman Jun 18 '21 at 11:22