springboot,如何通过注解获取当前所在注解位置的方法的名称,谢谢各位帮忙解答。
假设有两个注解@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);
}
}
}
}
}
https://blog.csdn.net/zsj777/article/details/93602954
首先AOP拦截所有的方法请求,然后利用反射去获取每个方法的注解,判断是否存在该注解,如果存在,则反射获取方法名称即可
其实注解的原理就是spring aop ,搞清楚了,也能更加理解和使用注解方式
https://blog.csdn.net/m0_37901418/article/details/83479893