java注解学习笔记

2019-07-11  本文已影响0人  crossyf

注解的定义

官方定义:Java注解用于为Java代码提供元数据。作为元数据,注解不直接影响你的代码执行,但也有一些类型的注解实际上可以用于这一目的。

代码演示

@Target({ElementType.PARAMETER, ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented 
public @interface TestAnnotation {
    String value() default "aaa";
    String message() default "message";
}

注解的定义使用@interface的关键字,其中修饰注解的叫做元注解元注解是可以注解到注解上的注解,或者说是一种基本的注解,但是他能够应用到其他的注解上面。

元注解

元注解一共有五种类型@Documented@Target@Inherited@Retention@Repeatable

@Documented: 作用是能够将注解中的元素包含到javadoc中去。

@Target:定义注解运用的地方。
1.ElementType.ANNOTATION_TYPE 可以给一个注解进行注解
2.ElementType.PARAMETER 可以给一个方法内的参数进行注解
3.ElementType.METHOD 可以给方法进行注解
4.ElementType.TYPE 可以给一个类型进行注解,比如类、接口、枚举
5.ElementType.PACKAGE 可以给包进行注解
6.ElementType.LOCAL_VARIABLE 可以给一个局部变量进行注解
7. ElementType.FIELD 可以给属性注解
8. ElementType.CONSTRUCTOR 可以给构造方法进行注解

@Inherited:继承,如果对A类进行了注解,并且该注解被@Inherited注解,当B类继承A类时,B类也会继承A类的注解。

@Retention:注解的保留期,即存活时间。有三个取值
1.RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时他讲被丢弃忽视
2.RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,会被加载进入到JVM中,在运行时可以获取到他们
3.RetentionPolicy.CLASS 注解客以保留到编译进行的时候,不会被加载到JVM中

@Repeatable:它表示一个注解可以有多个取值。

属性

在上面的例子中注解的内部有两个属性valuemessage,并且有默认值,在使用注解的时候可以不用赋值

@TestAnnotation(value="test",message="testmessage")
public void test() {

}

或者

@TestAnnotation()
public void test() {

}

用法

java注解的使用场景很多,这里我用一下公司项目中所用到的日志功能举一个例子。
定义注解

/**
 * 日志注解类
 * @author crossyf
 *
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented 
public @interface  LogRecord {
    String actionType() default "默认动作类型";
    String bussinessLogic() default "默认业务逻辑";
}

使用注解

 @RequestMapping("/index")
 @LogRecord(actionType = "系统", bussinessLogic = "进入系统首页")
 public String index(ModelMap modelMap, HttpServletRequest request) {
        Integer identityType = UserContext.getUserContext().getUserInfo().getIdentityType();
        modelMap.put("identityType", identityType);
        String upId = UserContext.getUserContext().getUserId();
        logger.info("------------index---------------" + upId);
        return "index";
    }

说明:这里在打开系统首页的方法中使用注解
解析注解

/**
 * 日志管理
 *
 * @author shuny
 */
@Component
public class OperationLogInteceptor extends HandlerInterceptorAdapter {
    @Autowired
    LogService logService;

    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView)
            throws Exception {
        //操作日志
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //获取注解的实例
            LogRecord logRecord = hm.getMethodAnnotation(LogRecord.class);

            if (logRecord != null) {
  
                UserContext userContext =
                        (UserContext) request.getSession().getAttribute(IController.USER_CONTEXT);
                if (userContext != null) {
                    String actionType = logRecord.actionType();
                    String bussinessLogic = logRecord.bussinessLogic();
                    Log log = new Log();
                    log.setCreateTime(new Date());
                    log.setModule(actionType);
                    String userid = UserContext.getUserContext().getUserId();
                    String userName = UserContext.getUserContext().getLoginName();
                    log.setUserId(userid);
                    log.setUserName(userName);
                    log.setOperation(bussinessLogic);
                    log.setIp(LoggerUtil.getCliectIp(request));
                    log.setContent(request.getQueryString() == null ? "" :
                            request.getQueryString().toString());
                    logService.save(log);
                }

            }
        }
    }

    /**
     * www
     * This implementation is empty.
     */
    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入方法之前进行拦截");
        return super.preHandle(request, response, handler);
    }
}

说明:使用java拦截器,在运行时进行拦截操作,这里解析出方法的注解,并且保存到数据库中。

注:本文部分内容节选自https://blog.csdn.net/briblue/article/details/73824058

上一篇 下一篇

猜你喜欢

热点阅读