利用Spring boot ResourceLoader可以获取指定package目录下所有的类和方法,其中关键的两个点是ResourcePatternResolver和CachingMetadataReaderFactory
具体实现方法:
@Autowired
private ResourceLoader resourceLoader;
@Override
public void run(String... args) throws Exception {
ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
Resource[] resources = resolver.getResources("classpath*:com/cxm/controller/**/*.class");
for (Resource resource : resources) {
MetadataReader reader = metaReader.getMetadataReader(resource);
String className = reader.getClassMetadata().getClassName();
Class<?> cla = Loader.loadClass(className);
Method[] ms = cla.getMethods();
for (Method m : ms) {
RequestMapping aa = m.getAnnotation(RequestMapping.class);
PostMapping bb = m.getAnnotation(PostMapping.class);
if (aa != null || bb != null) {
System.out.println(m);
}
}
}
}