談?wù)凧ava中自定義注解及使用場(chǎng)景
Java自定義注解一般使用場(chǎng)景為:自定義注解+攔截器或者AOP,使用自定義注解來(lái)自己設(shè)計(jì)框架,使得代碼看起來(lái)非常優(yōu)雅。本文將先從自定義注解的基礎(chǔ)概念說(shuō)起,然后開(kāi)始實(shí)戰(zhàn),寫(xiě)小段代碼實(shí)現(xiàn)自定義注解+攔截器,自定義注解+AOP。
一. 什么是注解(Annotation)
Java注解是什么,以下是引用自維基百科的內(nèi)容
Java注解又稱(chēng)Java標(biāo)注,是JDK5.0版本開(kāi)始支持加入源代碼的特殊語(yǔ)法元數(shù)據(jù)。
Java語(yǔ)言中的類(lèi)、方法、變量、參數(shù)和包等都可以被標(biāo)注。和Javadoc不同,Java標(biāo)注可以通過(guò)反射獲取標(biāo)注內(nèi)容。在編譯器生成類(lèi)文件時(shí),標(biāo)注可以被嵌入到字節(jié)碼中。Java虛擬機(jī)可以保留標(biāo)注內(nèi)容,在運(yùn)行時(shí)可以獲取到標(biāo)注內(nèi)容。當(dāng)然它也支持自定義Java標(biāo)注。
二. 注解體系圖
元注解:java.lang.annotation中提供了元注解,可以使用這些注解來(lái)定義自己的注解。主要使用的是Target和Retention注解
注解處理類(lèi):既然上面定義了注解,那得有辦法拿到我們定義的注解啊。java.lang.reflect.AnnotationElement接口則提供了該功能。注解的處理是通過(guò)java反射來(lái)處理的。
如下,反射相關(guān)的類(lèi)Class, Method, Field都實(shí)現(xiàn)了AnnotationElement接口。
因此,只要我們通過(guò)反射拿到Class, Method, Field類(lèi),就能夠通過(guò)getAnnotation(Class<T>)拿到我們想要的注解并取值。
三. 常用元注解
Target:描述了注解修飾的對(duì)象范圍,取值在java.lang.annotation.ElementType定義,常用的包括:
METHOD:用于描述方法 PACKAGE:用于描述包 PARAMETER:用于描述方法變量 TYPE:用于描述類(lèi)、接口或enum類(lèi)型Retention: 表示注解保留時(shí)間長(zhǎng)短。取值在java.lang.annotation.RetentionPolicy中,取值為:
SOURCE:在源文件中有效,編譯過(guò)程中會(huì)被忽略 CLASS:隨源文件一起編譯在class文件中,運(yùn)行時(shí)忽略 RUNTIME:在運(yùn)行時(shí)有效只有定義為RetentionPolicy.RUNTIME時(shí),我們才能通過(guò)注解反射獲取到注解。
所以,假設(shè)我們要自定義一個(gè)注解,它用在字段上,并且可以通過(guò)反射獲取到,功能是用來(lái)描述字段的長(zhǎng)度和作用。
@Target(ElementType.FIELD) // 注解用于字段上@Retention(RetentionPolicy.RUNTIME) // 保留到運(yùn)行時(shí),可通過(guò)注解獲取public @interface MyField { String description(); int length();}
四. 示例-反射獲取注解
先定義一個(gè)注解:
@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface MyField { String description(); int length();}
通過(guò)反射獲取注解
public class MyFieldTest { //使用我們的自定義注解 @MyField(description = '用戶(hù)名', length = 12) private String username; @Test public void testMyField() { // 獲取類(lèi)模板 Class c = MyFieldTest.class; // 獲取所有字段 for (Field f : c.getDeclaredFields()) { // 判斷這個(gè)字段是否有MyField注解 if (f.isAnnotationPresent(MyField.class)) { MyField annotation = f.getAnnotation(MyField.class); System.out.println('字段:[' + f.getName() + '], 描述:[' + annotation.description() + '], 長(zhǎng)度:[' + annotation.length() + ']'); } } }}
運(yùn)行結(jié)果
應(yīng)用場(chǎng)景一:自定義注解+攔截器 實(shí)現(xiàn)登錄校驗(yàn)
接下來(lái),我們使用springboot攔截器實(shí)現(xiàn)這樣一個(gè)功能,如果方法上加了@LoginRequired,則提示用戶(hù)該接口需要登錄才能訪問(wèn),否則不需要登錄。
首先定義一個(gè)LoginRequired注解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface LoginRequired {}
然后寫(xiě)兩個(gè)簡(jiǎn)單的接口,訪問(wèn)sourceA,sourceB資源
@RestControllerpublic class IndexController { @GetMapping('/sourceA') public String sourceA() { return '你正在訪問(wèn)sourceA資源'; } @GetMapping('/sourceB') public String sourceB() { return '你正在訪問(wèn)sourceB資源'; }}
沒(méi)添加攔截器之前成功訪問(wèn)
實(shí)現(xiàn)spring的HandlerInterceptor 類(lèi)先實(shí)現(xiàn)攔截器,但不攔截,只是簡(jiǎn)單打印日志,如下:
public class SourceAccessInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println('進(jìn)入攔截器了'); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }}
實(shí)現(xiàn)spring類(lèi)WebMvcConfigurer,創(chuàng)建配置類(lèi)把攔截器添加到攔截器鏈中
@Configurationpublic class InterceptorTrainConfigurer implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SourceAccessInterceptor()).addPathPatterns('/**'); }}
攔截成功如下
在sourceB方法上添加我們的登錄注解@LoginRequired
@RestControllerpublic class IndexController { @GetMapping('/sourceA') public String sourceA() { return '你正在訪問(wèn)sourceA資源'; } @LoginRequired @GetMapping('/sourceB') public String sourceB() { return '你正在訪問(wèn)sourceB資源'; }}
簡(jiǎn)單實(shí)現(xiàn)登錄攔截邏輯
@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println('進(jìn)入攔截器了'); // 反射獲取方法上的LoginRequred注解 HandlerMethod handlerMethod = (HandlerMethod) handler; LoginRequired loginRequired = handlerMethod.getMethod().getAnnotation(LoginRequired.class); if (loginRequired == null) { return true; } // 有LoginRequired注解說(shuō)明需要登錄,提示用戶(hù)登錄 response.setContentType('application/json; charset=utf-8'); response.getWriter().print('你訪問(wèn)的資源需要登錄'); return false;}
運(yùn)行成功,訪問(wèn)sourceB時(shí)需要登錄了,訪問(wèn)sourceA則不用登錄
應(yīng)用場(chǎng)景二:自定義注解+AOP 實(shí)現(xiàn)日志打印
先導(dǎo)入切面需要的依賴(lài)包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId></dependency>
定義一個(gè)注解@MyLog
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MyLog {}
定義一個(gè)切面類(lèi),見(jiàn)如下代碼注釋理解:
@Aspect // 1.表明這是一個(gè)切面類(lèi)@Componentpublic class MyLogAspect { // 2. PointCut表示這是一個(gè)切點(diǎn),@annotation表示這個(gè)切點(diǎn)切到一個(gè)注解上,后面帶該注解的全類(lèi)名 // 切面最主要的就是切點(diǎn),所有的故事都圍繞切點(diǎn)發(fā)生 // logPointCut()代表切點(diǎn)名稱(chēng) @Pointcut('@annotation(me.zebin.demo.annotationdemo.aoplog.MyLog)') public void logPointCut() {}; // 3. 環(huán)繞通知 @Around('logPointCut()') public void logAround(ProceedingJoinPoint joinPoint) { // 獲取方法名稱(chēng) String methodName = joinPoint.getSignature().getName(); // 獲取入?yún)? Object[] param = joinPoint.getArgs(); StringBuilder sb = new StringBuilder(); for (Object o : param) { sb.append(o + '; '); } System.out.println('進(jìn)入[' + methodName + ']方法,參數(shù)為:' + sb.toString()); // 繼續(xù)執(zhí)行方法 try { joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } System.out.println(methodName + '方法執(zhí)行結(jié)束'); }}
在步驟二中的IndexController寫(xiě)一個(gè)sourceC進(jìn)行測(cè)試,加上我們的自定義注解:
@MyLog@GetMapping('/sourceC/{source_name}')public String sourceC(@PathVariable('source_name') String sourceName){ return '你正在訪問(wèn)sourceC資源';}
啟動(dòng)springboot web項(xiàng)目,輸入訪問(wèn)地址
到此這篇關(guān)于談?wù)凧ava中自定義注解及使用場(chǎng)景的文章就介紹到這了,更多相關(guān)Java 自定義注解內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
