通過自定義注解,可以輕松在方法或者類執(zhí)行時去前置執(zhí)行各種想要的方法
先導(dǎo)入pom坐標
<!-- AOP依賴模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- web依賴相關(guān) -->
<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.準備完整服務(wù)鏈 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方法執(zhí)行完畢...");
}
}
@Service
public class SysLogServiceImpl implements SysLogService {
//中間接口就不貼上來了
@Override
public void save() {
System.out.println("執(zhí)行了impl_save方法");
}
@Override
public void myInterface() {
System.out.println("執(zhí)行了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("切點執(zhí)行1");
LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
System.out.println("切點執(zhí)行2");
Object object = joinPoint.proceed();
System.out.println("切點執(zhí)行3");
sysLogService.myInterface();
System.out.println("切點執(zhí)行4");
}
}
例如設(shè)置端口是8099的話,啟動訪問
http://localhost:8089/info3
得到如下結(jié)果
image.png
后續(xù)待補充,感覺這個是比較簡單的實例了