41

We have a quite big spring mvc web application where the controllers are annotated with @Controller and the methods with @RequestMapping.

I would like to create a test now which checks every possible url and checks if the return value is 200.

Is it somehow possible to get all the mappings from spring ?

mjspier
  • 6,386
  • 5
  • 33
  • 43

1 Answers1

50

I am replicating one of my previous answers here:

If you are using Spring 3.1 this handlerMapping component is an instance of RequestMappingHandlerMapping, which you can query to find the handlerMappedMethods and the associated controllers, along these lines(if you are on an older version of Spring, you should be able to use a similar approach):

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Controller
public class EndpointDocController {
 private final RequestMappingHandlerMapping handlerMapping;

 @Autowired
 public EndpointDocController(RequestMappingHandlerMapping handlerMapping) {
  this.handlerMapping = handlerMapping;
 }

 @RequestMapping(value="/endpointdoc", method=RequestMethod.GET)
 public void show(Model model) {
  model.addAttribute("handlerMethods", this.handlerMapping.getHandlerMethods());
 } 
}

I have provided more details on this at this url http://biju-allandsundry.blogspot.com/2012/03/endpoint-documentation-controller-for.html

This is based on a presentation on Spring 3.1 by Rossen Stoyanchev of Spring Source.

Community
  • 1
  • 1
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
  • 1
    Would this also list any mapping registered with the BeanNameUrlHandlerMapping? – user48956 Aug 18 '14 at 22:56
  • When using multiple RequestMappingHandlerMappings (such as with OAuth), this gives the error "No unique bean of type [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] is defined: expected single matching bean but found 2: [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0, oauth2HandlerMapping]". To fix it, change to List – Justin Killen Jul 09 '15 at 16:37
  • 1
    This does not include endpoints created with the `@FrameworkEndpoint`, only endpoints associated with `@Controller` and `@RestController` annotations – cosbor11 Jul 12 '17 at 08:38
  • 2
    Using/defining @Autowired private RequestMappingHandlerMapping handlerMapping; In class also works instead of defining final and having to pass it as argument and initialize it in constructor, Later on if you use a custom user made object (obviously not a controller) to initialize. It can be a problem – Merv Apr 04 '18 at 15:08