3

I created many controllers having each their requestmapping specified in order for them to be identified in the app :

enter image description here

package com.ambre.hib.controller;

@Controller
@RequestMapping("/")
public class HomeController {

    ...

}

package com.ambre.hib.controller;

@Controller
@RequestMapping("/ajax")
public class AjaxController {

    ...

}

So how to get programmatically all the value of the requestmappings of all controllers in the project ? I want to get something like a list containing for example "/" , "/ajax".

pheromix
  • 18,213
  • 29
  • 88
  • 158

1 Answers1

1

You can achieve this by using Google Guava and Java Reflection API.

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>19.0</version>
</dependency>

Google Guava includes a class ClassPath with three methods to scan for top level classes, in that you can use getTopLevelClasses(String packageName)

Refer this example code.

public void getClassOfPackage(String packagenom) {

    final ClassLoader loader = Thread.currentThread()
            .getContextClassLoader();
    try {

        ClassPath classpath = ClassPath.from(loader); // scans the class path used by classloader
        for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses(packagenom)) {
         if(!classInfo.getSimpleName().endsWith("_")){
            System.out.println(classInfo.getSimpleName());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

Below code will print all @RequestMapping from a single controller, you can update this code.

 Class clazz = Class.forName("com.abc.cbe.rest.controller.MyController"); // or list of controllers, //you can iterate that list
    for(Method method :clazz.getMethods()){
         for(Annotation annotation :method.getDeclaredAnnotations()){
             if(annotation.toString().contains("RequestMapping"))
            System.out.println("Annotation is..."+ annotation.toString());
     }
     }
Sundararaj Govindasamy
  • 8,180
  • 5
  • 44
  • 77