java之aop使用及自定義注解


目的:

  1.Java注解簡介

  2.Java元注解(重點)

  3.自定義注解

      案例一(獲取類與方法上的注解值)

      案例二(獲取類屬性上的注解屬性值)

      案例三(獲取參數修飾注解對應的屬性值)

       4.Aop自定義注解的應用(重點)

 


 

Java注解簡介

1. Java注解(Annotation)

   Java注解是附加在代碼中的一些元信息,用於一些工具在編譯、

   運行時進行解析和使用,起到說明、配置的功能。

   注解相關類都包含在java.lang.annotation包中。

 

2. Java注解分類

  2.1 JDK基本注解

  2.2 JDK元注解

  2.3 自定義注解

 

3. JDK基本注解

  3.1 @Override

      重寫

 

  3.2 @Deprecated

      已過時

 

  3.3 @SuppressWarnings(value = "unchecked")

 

      壓制編輯器警告

 


 

Java元注解

  作用:元注解用於修飾其他的注解

  • @Retention:定義注解的保留策略

 

    @Retention(RetentionPolicy.SOURCE) //注解僅存在於源碼中,在class字節碼文件中不包含 @Retention(RetentionPolicy.CLASS) //默認的保留策略,注解會在class字節碼文件中存在,但運行時無法獲得, @Retention(RetentionPolicy.RUNTIME) //注解會在class字節碼文件中存在,在運行時可以通過反射獲取到

 

  • @Target:指定被修飾的Annotation可以放置的位置(被修飾的目標)

 

      @Target(ElementType.TYPE)                      //接口、類
      @Target(ElementType.FIELD)                     //屬性
      @Target(ElementType.METHOD)                    //方法
      @Target(ElementType.PARAMETER)                 //方法參數
      @Target(ElementType.CONSTRUCTOR)               //構造函數
      @Target(ElementType.LOCAL_VARIABLE)            //局部變量
      @Target(ElementType.ANNOTATION_TYPE)           //注解
      @Target(ElementType.PACKAGE)                   // 

 注:可以指定多個位置,例如:

@Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和類上面使用

 

  • @Inherited:指定被修飾的Annotation將具有繼承性

 

@Documented:指定被修飾的該Annotation可以被javadoc工具提取成文檔.

 


自定義注解

注解分類(根據Annotation是否包含成員變量,可以把Annotation分為兩類):

標記Annotation:

沒有成員變量的Annotation; 這種Annotation僅利用自身的存在與否來提供信息

元數據Annotation:

 包含成員變量的Annotation; 它們可以接受(和提供)更多的元數據;

如何自定義注解?

使用@interface關鍵字, 其定義過程與定義接口非常類似, 需要注意的是:

   Annotation的成員變量在Annotation定義中是以無參的方法形式來聲明的, 其方法名和返回值類型定義了該成員變量的名字和類型,

   而且我們還可以使用default關鍵字為這個成員變量設定默認值;

 

注意:只有名字為value”屬性,賦值時可以省略屬性名

 

案例一(獲取類與方法上的注解值):

  TranscationModel

package com.huangting.annotation.P1; /** * enum枚舉 */
public enum TranscationModel { Read, ReadWrite, Write }

  MyAnnotation1

package com.huangting.annotation.P1; import java.lang.annotation.*; /** * MyAnnotation1注解可以用在類、接口、屬性、方法上 * 注解運行期也保留 * 不可繼承 */ @Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAnnotation1 { String name(); }

  MyAnnotation2

package com.huangting.annotation.P1; import java.lang.annotation.*; /** * MyAnnotation2注解可以用在方法上 * 注解運行期也保留 * 不可繼承 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAnnotation2 { TranscationModel model() default TranscationModel.ReadWrite; }

   MyAnnotation3

package com.huangting.annotation.P1; import java.lang.annotation.*; /** * MyAnnotation3注解可以用在方法上 * 注解運行期也保留 * 可繼承 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface MyAnnotation3 { TranscationModel[] models() default TranscationModel.ReadWrite; }

 Dome1

package com.huangting.annotation.P1; /** * 獲取類與方法上的注解值 */ @MyAnnotation1(name = "abc") public class Demo1 { @MyAnnotation1(name = "xyz") private Integer age; @MyAnnotation2(model = TranscationModel.Read) public void list() { System.out.println("list"); } @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write}) public void edit() { System.out.println("edit"); } }

Demo1Test

package com.huangting.annotation.P1; import org.junit.Test; public class Demo1Test { @Test public void list() throws Exception { // 獲取類上的注解
        MyAnnotation1 annotation1 = Demo1.class.getAnnotation(MyAnnotation1.class); System.out.println(annotation1.name());//abc // 獲取方法上的注解
        MyAnnotation2 myAnnotation2 = Demo1.class.getMethod("list").getAnnotation(MyAnnotation2.class); System.out.println(myAnnotation2.model());//Read } @Test public void edit() throws Exception { MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class); for (TranscationModel model : myAnnotation3.models()) { System.out.println(model);//Read,Write
 } } }

效果:

 

 

 注意:

jar包的運用中最好不要出現test,把《scope》《/scope》刪除即可

否則會報錯@Test無法使用

 

案例二(獲取類屬性上的注解屬性值)

TestAnnotation

package com.huangting.annotation.P2; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface TestAnnotation { String value() default "默認value值"; String what() default "這里是默認的what屬性對應的值"; }

Dome2

package com.huangting.annotation.P2; /** * 獲取類屬性上的注解屬性值 */
public class Demo2 { @TestAnnotation(value = "這就是value對應的值_msg1", what = "這就是what對應的值_msg1") private static String msg1; @TestAnnotation("這就是value對應的值1") private static String msg2; @TestAnnotation(value = "這就是value對應的值2") private static String msg3; @TestAnnotation(what = "這就是what對應的值") private static String msg4; }
Demo2Test 
package com.huangting.annotation.P2; import org.junit.Test; public class Demo2Test { @Test public void test1() throws Exception { TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class); System.out.println(msg1.value()); System.out.println(msg1.what()); } @Test public void test2() throws Exception{ TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class); System.out.println(msg2.value()); System.out.println(msg2.what()); } @Test public void test3() throws Exception{ TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class); System.out.println(msg3.value()); System.out.println(msg3.what()); } @Test public void test4() throws Exception{ TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class); System.out.println(msg4.value()); System.out.println(msg4.what()); } }

效果:

 

案例三(獲取參數修飾注解對應的屬性值):

IsNotNull 
package com.huangting.annotation.P3; import java.lang.annotation.*; /** * 非空注解:使用在方法的參數上,false表示此參數可以為空,true不能為空 */ @Documented @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface IsNotNull { boolean value() default false; }
Demo3 
package com.huangting.annotation.P3; /** * 獲取參數修飾注解對應的屬性值 */
public class Demo3 { public void hello1(@IsNotNull(true) String name) { System.out.println("hello:" + name); } public void hello2(@IsNotNull String name) { System.out.println("hello:" + name); } }
Demo3Test 
package com.huangting.annotation.P3; import org.junit.Test; import java.lang.reflect.Parameter; public class Demo3Test { @Test public void hello1() throws Exception { Demo3 demo3 = new Demo3(); for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) { IsNotNull annotation = parameter.getAnnotation(IsNotNull.class); if(annotation != null){ System.out.println(annotation.value());//true
 } } } @Test public void hello2() throws Exception { Demo3 demo3 = new Demo3(); for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) { IsNotNull annotation = parameter.getAnnotation(IsNotNull.class); if(annotation != null){ System.out.println(annotation.value());//false
 } } } }

效果:

 

 

 


Aop自定義注解的應用

  MyLog 

package com.huangting.annotation.Aop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyLog { String desc(); }

 

MyLogAspect 
package com.huangting.annotation.Aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component @Aspect public class MyLogAspect { private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class); /** * 只要用到了com.huangting.annotation.Aop.MyLog這個注解的,就是目標類 */ @Pointcut("@annotation(com.huangting.annotation.Aop.MyLog)") private void MyValid() { } @Before("MyValid()") public void before(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); MyLog myLog = signature.getMethod().getAnnotation(MyLog.class); System.out.println("[" + signature.getName() + " : start.....]"); System.out.println("【目標對象方法被調用時候產生的日志,記錄到日志表中】:"+myLog.desc()); } }
BaseTestCase 
package com.huangting.annotation.Aop; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class BaseTestCase { }
LogController 
package com.huangting.annotation.Aop; import org.springframework.stereotype.Component; @Component public class LogController { @MyLog(desc = "這是結合spring aop知識,講解自定義注解應用的一個案例") public void testLogAspect(){ System.out.println("牆頭馬上遙相顧"); } }
LogControllerTest 
package com.huangting.annotation.Aop; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class LogControllerTest extends BaseTestCase { @Autowired private LogController logController; @Test public void testLogAspect(){ logController.testLogAspect(); } }

效果:

 

 

謝謝觀看!

 


免責聲明!

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



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