springboot中獲取指定包下的包含某個注解的全部類


需求

獲取spring項目里的帶有某個注解的全部類

難點
需要掃描指定包路徑下的類,同時也要掃描其下所有子包

思路

可以自己實現,推薦使用spring的工具類

代碼

package com.example.demo;

import com.example.demo.annos.MyAnno;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    private final String BASE_PACKAGE = "com.example.demo";
    private final String RESOURCE_PATTERN = "/**/*.class";

    @Test
    public void test() {
        Map<String, Class> handlerMap = new HashMap<String, Class>();

        //spring工具類,可以獲取指定路徑下的全部類
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN;
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            //MetadataReader 的工廠類
            MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                //用於讀取類信息
                MetadataReader reader = readerfactory.getMetadataReader(resource);
                //掃描到的class
                String classname = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(classname);
                //判斷是否有指定主解
                MyAnno anno = clazz.getAnnotation(MyAnno.class);
                if (anno != null) {
                    //將注解中的類型值作為key,對應的類作為 value
                    handlerMap.put(classname, clazz);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
        }
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM