了解自定义注解详细解释
开头总结(具体代码在下面)
方法上的注解内容可以直接获取、类上的需要强转
方法上自定义注解内容提取
/**
* Log代表method所在类
*/
String doType = method.getAnnotation(Log.class).doType();
类上自定义注解内容提取
/**
* clazz代表有Module这个自定义注解的类
*/
String value = (Module)clazz.getAnnotation(Module.class).value();
Annotation annotation = clazz.getAnnotation(Module.class);
Module module = (Module) annotation;
String value = module.value();
方法上的自定义注解
自定义注解
/**
* 自定义日志注解
* @author Kuwei
* ElementType.METHOD 表明是方法上使用的注解
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/** 要执行的操作类型比如:add操作 **/
String doType() default "";
/** 要执行的具体操作比如:添加用户 **/
String doName() default "";
}
注解使用
@Controller
@RequestMapping("bankLogCtrl")
public class BankLogController {
@RequestMapping("getLogs")
@Log(doType = "select",doName = "日志列表")
public @ResponseBody Map<String,Object> getLogs(Integer page) throws Exception {
...
return map;
}
}
注解内容提取
@After("controllerAspect()")
public void after(JoinPoint joinPoint) throws Throwable {
try {
String targetName = joinPoint.getTarget().getClass().getName()
String methodName = joinPoint.getSignature().getName()
Object[] arguments = joinPoint.getArgs()
Class targetClass = Class.forName(targetName)
Method[] methods = targetClass.getMethods()
String doType = ""
String doName = ""
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes()
if (clazzs.length == arguments.length) {
//方法上的注解内容提取
doType = method.getAnnotation(Log.class).doType()
doName = method.getAnnotation(Log.class).doName()
break
}
}
}
}
类上的自定义注解
自定义注解
/**
* 自定义模块注解
* @author Kuwei
* ElementType.TYPE 表明类上使用的注解
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Module {
String value() default "";
}
注解使用
@Module("登录模块")
@Controller
@RequestMapping("bankLogCtrl")
public class BankLogController {
...
}
注解内容提取
@After("controllerAspect()")
public void after(JoinPoint joinPoint) throws Throwable {
String targetName = joinPoint.getTarget().getClass().getName();
Class clazz= Class.forName(targetName);
try {
boolean has = clazz.isAnnotation();
if (has) {
Annotation annotation = clazz.getAnnotation(Module.class);
Module module = (Module) annotation;
exception_model_name = module.value();
}
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}