1、切面场景
无侵入的实现功能增强
2、实现
切面类的实现
需要使用注解@Aspect和Componet来实现,
环绕通知的作用在返回的student的sname后面拼接around字符串。
后置通知的作用在入参后面拼接idididdi,然后打印日志
@Aspect
@Component
public class StudentBeforeAspect {
@Pointcut("@annotation(com.nio.annotation.StudentBeforeAopAnnotation)")
public void studentBefortAspect(){}
@AfterReturning(value = "studentBefortAspect()")
public void addInfo(JoinPoint joinPoint){
final Object[] args = joinPoint.getArgs();
if (ObjectUtils.isNotEmpty(args)){
for (Object arg : args) {
if (arg instanceof String){
String id = String.valueOf(arg) + "idididdi";
System.out.println("id is " + id);
}
}
}
}
@Around(value = "studentBefortAspect()")
public Object addInfo(ProceedingJoinPoint proceedingJoinPoint){
StudentInfo result = null;
final Object[] args = proceedingJoinPoint.getArgs();
try {
Object proceed = proceedingJoinPoint.proceed(args);
if (Objects.nonNull(proceed)) {
if (proceed instanceof StudentInfo) {
result = (StudentInfo) proceed;
result.setSname(result.getSname() + "aroud");
return result;
}
}
} catch (Throwable e) {
throw new RuntimeException(e);
}
return result;
}
}
注解的实现
自定义注解来实现切点方法的定位
@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentBeforeAopAnnotation {
}
切点方法
@StudentBeforeAopAnnotation
public StudentInfo getById(String id) {
return studentDomainService.getById(id);
}
运行结果