创建一个springboot工程
pom文件中增加
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
自定义一个注解
@Retention(RetentionPolicy.RUNTIME)//定义注解的使用范围,编译时,还是运行时。。。
@Target(ElementType.METHOD)//定义注解用在哪里class,method。。。
public @interface Login {
String value() default "";
}
定义一个aop的类
@Aspect
@Component
public class MyAop {
@Pointcut("execution(public * com.company.aop.annotation.aopannotation.controller.DemoController.*(..))")
public void pt(){}
@Before("pt()")
public void deBefore(JoinPoint joinPoint) {
try {
Class clazz = joinPoint.getTarget().getClass();
String methodName = joinPoint.getSignature().getName();
Method method = clazz.getDeclaredMethod(methodName,new Class[]{String.class});
Login loginAnno = method.getAnnotation(Login.class);
if(loginAnno!=null){
System.out.println("检查用户是否登录");
}else{
System.out.println("不用检查用户是否登录");
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
启动类
@SpringBootApplication
@EnableAspectJAutoProxy
public class AopAnnotationApplication {
public static void main(String[] args) {
SpringApplication.run(AopAnnotationApplication.class, args);
}
}
controller类
@RestController
public class DemoController {
@GetMapping("hello1")
@Login
public String hello1(String name){
return "hello1:"+name;
}
@GetMapping("hello2")
public String hello2(String name){
return "hello2:"+name;
}
}
访问http://localhost:8080/hello2?name=zhangsan不需要登录检查
访问http://localhost:8080/hello1?name=zhangsan需要登录检查