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/hello和http://localhost:8080/aspect/hello2,然后去看代码,可以看到注解中的配置已经被读取到了,而且在运行两个接口之前,切面也成功的切入进去了。这样就大功告成了。