Spring相信大家都学过,就不多述了。
自定义注解,注解的类中所有的接口都会执行AOP增强,注解的接口会执行AOP增强。
注解类:
package xin.students.examManagement.annotation.springConfiguration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 目标方法上添加@UserIfLogin注解,可以在AOP切面中进行拦截,并执行相应的登录验证逻辑
* 这个类本身并不会直接执行任何登录验证逻辑,它只是作为一个标记,用于告诉AOP切面在哪些方法上应该执行登录验证
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresLogin {
}
AOP增强类:
package xin.students.examManagement.Aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* 验证是否登录的AOP
*/
@Aspect
@Component
public class IfLoginAspect {
//这个切点表达式的作用是确定需要拦截和执行切面逻辑的方法,包括添加了@RequiresLogin注解的方法以及添加了@RequiresLogin注解的类的所有方法。
@Before("@annotation(xin.students.examManagement.annotation.springConfiguration.RequiresLogin) || @within(xin.students.examManagement.annotation.springConfiguration.RequiresLogin)")
public void validateLogin(JoinPoint joinPoint) {
System.out.println("开始登录验证");
}
}
SpringBoot主类:
@SpringBootApplication
@EnableAspectJAutoProxy //开始AOP配置
@ComponentScan(basePackages = "xin.students.examManagement.*")
public class ExamManagementApplication {
public static void main(String[] args) {
SpringApplication.run(ExamManagementApplication.class, args);
}
}
测试类:
package xin.students.examManagement.configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.students.examManagement.annotation.springConfiguration.RequiresLogin;
@RestController
@RequiresLogin
public class TestController {
@GetMapping("/secure-page")
public String securePage() {
// 这个方法需要登录验证
return "Secure Page";
}
@GetMapping("/public-page")
public String publicPage() {
// 这个方法不需要登录验证
return "Public Page";
}
}
添加依赖!
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.13</version>
</dependency>
如果你给Service加AOP,给Service所继承的接口加,不要给Service本身加,要不会报错的。
如果想改变其返回值,就通过@Around注解。
@AfterThrowing(pointcut = "execution(* xin.students.service.TaxExemptionService.*(..))", throwing = "ex")
public void handleException(Exception ex) {
System.out.println("出错了");
}
@Around("execution(* xin.students.service.TaxExemptionService.*(..))")
public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {
try {
return joinPoint.proceed(); // 执行目标方法
} catch (Exception ex) {
// 这里可以添加日志记录异常信息
return new ResponseEntity<>("no", HttpStatus.BAD_REQUEST);
}
}