springboot,如何通过注解获取当前所在注解位置的方法的名称,谢谢各位帮忙解答。
4条回答 默认 最新
- Kevin.Y.K 2019-09-26 09:42关注
假设有两个注解@OpenAPI(类)、@OpenAPIMethod(方法),示例如下
@WebListener public class SpringContextLoader implements ApplicationContextAware, ServletContextListener { private final static Logger logger = LoggerFactory.getLogger(SpringContextLoader.class); private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } public void contextInitialized(ServletContextEvent sce) { // 装载Spring的Context try { if(applicationContext==null) { applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext()); } logger.info("系统spring配置装载成功~"); } catch (Exception e) { logger.error("系统spring配置装载失败", e); } } /** * 通过注解得到类型 * * @param clazz * @return */ public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> clazz) { return applicationContext.getBeansWithAnnotation(clazz); } /** * 得到Class中包含有传入Annotation类型的方法 * * @param clz * Class类型 * @param annoClz * Annotation类型 * @return 传入Annotation类型标记的方法 * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static List<Method> getClassMethodByAnnotation(Class clz, Class annoClz) throws Exception { clz = Class.forName(clz.getName(), true, clz.getClassLoader()); List<Method> result = new ArrayList<Method>(); for (Method method : clz.getMethods()) { if (method.getAnnotation(annoClz) != null) { result.add(clz.getMethod(method.getName(), method.getParameterTypes())); } } return result; } /** * 打印注解对应的方法名 * @throws Exception */ public static void printMethodName() throws Exception{ Map<String, Object> openClz = SpringContextLoader.getBeansWithAnnotation(OpenAPI.class); if (openClz != null) { for (Object clzObj : openClz.values()) { List<Method> methodList = getClassMethodByAnnotation(clzObj.getClass(), OpenAPIMethod.class); for (Method method : methodList) { String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName(); System.out.println(methodName); } } } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题
- ¥15 slam rangenet++配置
- ¥15 有没有研究水声通信方面的帮我改俩matlab代码
- ¥15 ubuntu子系统密码忘记
- ¥15 保护模式-系统加载-段寄存器