Help us understand the problem. What is going on with this article?

Spring bootのControllerクラスで定義したパスを一覧として取得する

More than 1 year has passed since last update.

SpringBootで構築したサイトのsitemap.xmlを作る際、Controllerクラスのメソッドに付いている@RequestMappingアノテーションの値を取得する方法を調べたのでメモ。

結論

例外やpath変数は無視して、とにかくアノテーションに定義されているパスの文字列を一覧として取得します。

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);
                    }));
        }
    }
}

要点

ClassPathScanningCandidateComponentProviderを使ってspringのメタデータを取得している部分が肝ですね。
それ以外は普通にリフレクションでメソッド取得して地道にアノテーションの値見ています。
現実的にsitemapにするには、変数を想定される値で置き換えたり、非公開のurl除外したり、諸々気をつけることあります。

参考

Java実行時にアノテーションが定義されたクラスを取得する方法

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away