美文网首页
java注解

java注解

作者: java部落 | 来源:发表于2017-11-10 23:05 被阅读0次

注解使用

Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
  注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。

元注解

元注解是指注解的注解。包括 @Retention 、@Target 、@Document 、@Inherited四种。

@Retention: 定义注解的保留策略

@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

@Target(ElementType)有:

1.CONSTRUCTOR:用于描述构造器

2.FIELD:用于描述域

3.LOCAL_VARIABLE:用于描述局部变量

4.METHOD:用于描述方法

5.PACKAGE:用于描述包

6.PARAMETER:用于描述参数

7.TYPE:用于描述类、接口(包括注解类型) 或enum声明

@Documented

  @****Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。

无参数注解

自定义无参数注解:

package com.xxx.annotation;
/**
 * Created by yang
 * 2016/7/25.
 */
public @interface ApiLog {
}

注解处理方法:

@Aspect
@Component
@Order(1)
public class ApiAspect {
    /**
     * 日志拦截处理,主要实现打印输入参数和输出参数
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("execution(@com.xxx.annotation.ApiLog * *(..))")
    public Object auditMethodCallLog(ProceedingJoinPoint pjp) throws Throwable {

    }
}

注解传参数

可以同时指定应用于多个Target,eg:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented

自定义注解:

/**
 * @author yang
 * @date 2017/10/23
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestAnnotation {
    String[] value() default {};

    String description() default "";

    boolean defaultPass() default false;
}

注解处理方法:

@Aspect
@Component
public class TestAnnotationAspect {
    @Around( value=" @annotation(testAnnotation)",argNames="pjp,testAnnotation")
    public Object testAspect(ProceedingJoinPoint pjp, TestAnnotation testAnnotation) throws Throwable {
        String des = testAnnotation.description();
        System.out.print(testAnnotation);
        return pjp.proceed();
    }
}

@TestAnnotation注解传入参数:

 @RequestMapping("/test")
    @TestAnnotation(description = "test description",defaultPass = true)
    public String test() {
        return "home";
    }

注解处理方法输出:

@com.demo.projects.common.TestAnnotation(defaultPass=true, value=[], description=test description)

注解 + 拦截器

登陆注解:

/**
 * @author yang
 * @date 2017/10/23
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AuthLogin {
    String redirectUrl() default "";
}

登陆拦截器+注解:

/**
 * @author yang
 * @date 2017/10/23
 */
public class AuthLoginInteceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod myHandlerMethod = (HandlerMethod) handler;
            Method method = myHandlerMethod.getMethod();
            AuthLogin authFlag = method.getAnnotation(AuthLogin.class);
            System.out.print(authFlag);
            boolean login = false;
            if (authFlag != null) {
                String redirectUrl = "http://www.demo.com";
                if(!StringUtils.isEmpty(authFlag.redirectUrl())){
                    redirectUrl = authFlag.redirectUrl();
                }
                if(!login) {//未登录
                    String redirectLoginUrl = "https://test.login.com/Login?redirect=" + URLEncoder.encode(redirectUrl, "utf-8");
                    response.sendRedirect(redirectLoginUrl);
                    return false;
                }
            }
            return true;
        }
        return super.preHandle(request, response, handler);
    }
}

spring boot配置拦截器:

/**
 * Created by yang on 2017/6/6.
 */
@Configuration
public class MyMvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthLoginInteceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

登陆注解使用:

 @RequestMapping("/login")
    @AuthLogin(redirectUrl = "http://www.baidu.com")
    public String loginAuth() {
        return "home";
    }

注解处理方法输出:

@com.demo.projects.common.AuthLogin(redirectUrl=http://www.baidu.com)

欢迎加入学习交流群569772982,大家一起学习交流。

相关文章

  • 菜鸟学服务端技术----Spirng基础

    注解 Java基础加强总结(一)——注解(Annotation) java中的注解是如何工作的? java 注解 ...

  • 自定义注解

    java annotation基础 java注解分为标准注解和元注解。 标准注解是java为我们提供的预定义的注解...

  • Java注解的使用

    Java注解的使用 参考 廖雪峰java教程 使用注解 什么是注解(Annotation)?注解是放在Java源码...

  • Java原生注解和Spring注解的说明

    注解 java 原生注解 Spring 中的注解 一 Java原生注解 Java注解是在JDK1.5以后引入的新特...

  • Java 注解

    JAVA注解 Java 自带注解(系统注解) @Override 表示重写注解 @Deprecated 表示过时的...

  • 1.8 Java 注解annotation

    1.1 注解声明 Java注解Annotation,有声明注解和元注解 元注解:Java提供的元注解,所谓元注解就...

  • Java注解学习总结(脑图)

    注解的提取测试:定义注解: 测试注解提取: 参考:《Java编程思想》java注解

  • Java注解

    Java注解(Annotation)详解(一)——概述及JDK自带注解 Java注解(Annotation)详解(...

  • JAVA-注解 Annotation

    JAVA-注解 Annotation sschrodinger 2018/6/4 基本 注解 Java 注解用于为...

  • Java注解简介篇

    摘要 本文详细介绍java注解是什么,如何声明java注解,如何解析java注解。最后介绍JDK提供的几大基本注解...

网友评论

      本文标题:java注解

      本文链接:https://www.haomeiwen.com/subject/kfiimxtx.html