LoginSignup
2
6

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-07-26

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実行時にアノテーションが定義されたクラスを取得する方法

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6