Java 注解的原理及自定义注解

1、@Deprecated与SupressWarnings("deprecation")
对于废弃的方法,我们会用注解@Deprecated来显示注解表示,但是有的时候我们用了废弃的@Deprecated注解,会出现 中横线,如果用了废弃的方法,又不想显示横线,可以添加注解@SupressWarnings("deprecation")

举个栗子:

public class DeprecateExample {
    
    @Deprecated
    public void sayHello() {
        System.out.println("hello");
    }
    
    @SuppressWarnings("deprecation")
    public void saySpeak() {
        this.sayHello();
    }
}
2、Java注解在项目中的具体应用?
用于:记录系统日志、登录验证(需要结合Spring AOP实现)

(1)自定义注解类LogRecord.java

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogRecord {
    
    String type() default "0"; // 短信发送模版id
    String message() default "message"; // 短信发送描述
}

(2)在Controller层进行注解类标记:

@LogRecord(type = "123", message = "记录行为")
@RequestMapping(value = "/testRecord")
public Result testRecord() throws CMSQueueException, CMSSendException {
    String mobileNo = "111111"; // 收信人手机号
    int smsType = 23064; // 申请的模版号
    String interCode = "86";
   ...
    return Result.builder().data("success").success().build();
}

(3)在AOP 切面类进行注解翻译:

@Aspect
@Component
@Slf4j
public class SmAspect {
    
    @Pointcut("@annotation(com.example.annotaion.LogRecord)")
    public void logRecord(){
    }

    @Before("logRecord()")
    public void doBefore(JoinPoint joinPoint) throws ClassNotFoundException {
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        int type = 0;
        for (Method method: methods) {
            if (method.getName().equalsIgnoreCase(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    type = method.getAnnotation(SmSend.class).type();
                    log.info("type is:{}", type);
                    break;
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/timchen525/article/details/80978214