Spring切面中實現自定義註解

1.首先寫出一個自定義註解。

package com.salong.aspect.test;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Login {
    String username() default "";
    String password() default "";
}

上面我們寫了一個Login的註解,其中包含了username和password兩個基本屬性,如何寫註解這裏不詳述,不清楚的可以先去補習。

2.自定義一個調用類,代碼如下:

package com.salong.aspect.test;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/aspect")
public class index {

    @RequestMapping("/hello")
    @Login(username = "小明1",password = "123")
    public void hello(){
        System.out.println("hello world");
    }

    @RequestMapping("/hello2")
    @Login(username = "小明2",password = "456")
    public void hello2(){
        System.out.println("hello world2");
    }
}

在這裏我們寫了兩個接口,分別是/aspect/hello和/aspect/hello2,都用了Login這個註解,但是註解的內容不一樣,一個是小明1,密碼123,一個是小明2,密碼456.

3.製作註解切面,代碼如下:

package com.salong.aspect.test;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class AspectDemo {
    
    //切入點爲使用了Login註解的任何地方
    @Pointcut("@annotation(com.salong.aspect.test.Login)")
    public void logPointCut() {

    }

    @Before(value = "logPointCut()")
    public void check(){

        System.out.println("check");
    }


    @After(value = "logPointCut()")
    public void bye(){


        System.out.println("bye");
    }



    @Around("logPointCut() && @annotation(login)")
    public Object around(ProceedingJoinPoint joinPoint, Login login){

        System.out.println("around");
        //輸出使用login註解時候的username屬性值
        System.out.println(login.username());
        //輸出使用login註解時候的passwo屬性值
        System.out.println(login.password());
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;
    }
}

這樣,所有的類就寫好了,運行項目,打開瀏覽器。分別測試一下hello和hello2這兩個接口,輸入:

http://localhost:8080/aspect/hellohttp://localhost:8080/aspect/hello2,然後去看代碼,可以看到註解中的配置已經被讀取到了,而且在運行兩個接口之前,切面也成功的切入進去了。這樣就大功告成了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章