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); } } } } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报