Java:深入自定义注解(Annotation)

 在网上找了很多资料也有写的比较好的,但是总有有一点半点的细节没有写出来,在这里自己总结下使用。

 使用Java的自定义注解,首先个人需要了解下Java为我们提供的元注解和相关定义注解的语法。(这个我在网上选择了一篇详细的介绍链接在文章最底层)


 

1、首先自定义我们需要的注解

package com.plat;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*
* @Retention(RetentionPolicy.SOURCE)
* 这个注解的意思是让MyAnnotation注解只在java源文件中存在,编译成.class文件后注解就不存在了
* @Retention(RetentionPolicy.CLASS)
* 这个注解的意思是让MyAnnotation注解在java源文件(.java文件)中存在,编译成.class文件后注解也还存在,
* 被MyAnnotation注解类标识的类被类加载器加载到内存中后MyAnnotation注解就不存在了
*/
/*
* 这里是在注解类MyAnnotation上使用另一个注解类,这里的Retention称为元注解。
* Retention注解括号中的"RetentionPolicy.RUNTIME"意思是让MyAnnotation这个注解的生命周期一直程序运行时都存在
*/
//Target注解决定MyAnnotation注解可以加在哪些成分上,如加在类身上,或者属性身上,或者方法身上等成分
/**
 * @author jwkang
 *是否需要判断权限,默认为true需要判断权限,设定为false的情况下不判断权限
 */
@Documented
@Inherited
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PlatPermission {
   
    boolean validate() default true;
}

2、将自定义注解标识在不需要判断权限的方法上

    @PlatPermission(validate=false)
    @RequestMapping(value = "/getSelect", method = {RequestMethod.POST})
    @ResponseBody
    public BaseOutModel GetSelect(String selectType) {
        BaseOutModel result = new BaseOutModel();
        LinkedHashMap<String, String> data = new LinkedHashMap<String, String>();
        try {
            
            if(!TypeOfEnum.contains(selectType))
            {
                result.setResult(false);
                result.setErrorMessage("未找到对应信息");
                return result;
            }
            TypeOfEnum typeOfEnum = TypeOfEnum.get(selectType);
            data = EnumHelp.getZEnumDesList(typeOfEnum.getType());
            result.setResult(true);
            result.setResponse(data);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("operateEmail err", e.toString());
            result.setResult(false);
            result.setErrorMessage("系统异常!请重试...");
            return result;
        }
        return result;
    }

3、进行权限的管控

    jar包的引用:

import org.springframework.web.method.HandlerMethod;

   权限的控制,注解读取

public class PlatHandlerInterceptorAdapter extends HandlerInterceptorAdapter {
    private static final ILog logger = LogManager.getLogger(PlatHandlerInterceptorAdapter.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //处理Permission Annotation,实现方法级权限控制 
        //HandlerMethod 需要对应Jar包的位置,否则会一直为false
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
             /*
             * 1、确认当前的controller是否需要进行权限判定,如果需要则进行验证。
             * 2、当controller不需要验证,则验证当前的方法是否需要权限验证,需要则进行验证,不需要则跳出
             * */
            //获取controller注解, controller检查是否需要验证权限控制 
            PlatPermission permission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(PlatPermission.class);
            if (permission != null && !permission.validate()) //不需要验证权限
            {
                return super.preHandle(request, response, handler);
            }
             //获取方法注解,方法检查是否需要验证权限控制
            permission = handlerMethod.getMethod().getAnnotation(PlatPermission.class);
            if (permission != null && !permission.validate()) //不需要验证权限
            {
                return super.preHandle(request, response, handler);
            }
             // 权限判断,没有权限则跳转至无权限页面,有权限则走正常流程
             xxxx
        }
        
        return super.preHandle(request, response, handler);
    } 
}

4、完成,整个一套的注解使用


  深入Java注解(非常推荐):http://www.cnblogs.com/digdeep/p/4525567.html 

 

posted @ 2017-03-22 17:09  鬼才  阅读(11601)  评论(0编辑  收藏  举报