When creating sitemap.xml of the site built with SpringBoot, I checked how to get the value of @RequestMapping annotation attached to the method of Controller class, so make a note.
Ignore exceptions and path variables, and get the path string defined in the annotation as a list anyway.
Test.java
import java.util.Arrays;
import java.util.Set;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
Set<BeanDefinition> beanSet = scanner.findCandidateComponents("/* controller package string */");
for (BeanDefinition def : beanSet) {
Class<?> clazz = Class.forName(def.getBeanClassName());
Arrays.stream(clazz.getDeclaredMethods()).map(m -> m.getAnnotation(RequestMapping.class)).filter(
a -> a != null && a.value().length > 0).forEach(a -> Arrays.stream(a.value()).forEach(p ->{
System.out.println(p);
}));
}
}
}
The part that gets the metadata of spring using ClassPathScanningCandidateComponentProvider It's the liver. Other than that, I usually get the method by reflection and steadily look at the value of the annotation. To make it a realistic sitemap, you need to be careful about replacing variables with expected values, excluding private urls, and so on.
How to get the class in which annotations are defined when Java is executed
Recommended Posts