通过自定义注解,可以轻松在方法或者类执行时去前置执行各种想要的方法
先导入pom坐标
<!-- AOP依赖模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- web依赖相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.先定义自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
String module() default "";
}
2.准备完整服务链 controller层,service层
@RestController
public class HelloWorldController {
@Autowired
private SysLogService helloWorldService;
@LogAnnotation
@RequestMapping(value = "/info3", method = RequestMethod.GET)
public void hello() {
System.out.println("进入controll层");
helloWorldService.save();
System.out.println("controller层save方法执行完毕...");
}
}
@Service
public class SysLogServiceImpl implements SysLogService {
//中间接口就不贴上来了
@Override
public void save() {
System.out.println("执行了impl_save方法");
}
@Override
public void myInterface() {
System.out.println("执行了impl_myInterface方法");
}
}
3.定义切面
@Aspect
@Component
public class LogAdvice {
@Autowired
private SysLogService sysLogService;
@Around(value = "@annotation(LogAnnotation)")
public Object logSave(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("进入到切点处理方法");
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
System.out.println("切点执行1");
LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
System.out.println("切点执行2");
Object object = joinPoint.proceed();
System.out.println("切点执行3");
sysLogService.myInterface();
System.out.println("切点执行4");
}
}
例如设置端口是8099的话,启动访问
http://localhost:8089/info3
得到如下结果
image.png
后续待补充,感觉这个是比较简单的实例了