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);
}
运行结果

文章介绍了如何使用SpringAOP中的@Aspect和@Component注解实现切面类,包括环绕通知和后置通知的使用。环绕通知用于在返回的student对象的sname后拼接around字符串,后置通知则在入参后面拼接idididdi并打印日志。自定义注解@StudentBeforeAopAnnotation用于定位切点方法,示例中展示了使用该注解的方法getById()。
854

被折叠的 条评论
为什么被折叠?



