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 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM