@Aspect @Component public class LoginLogAspect {
private static final Logger logger = LoggerFactory.getLogger(LoginLogAspect.class);
@Pointcut("execution(* com.javayouxue.service.UserService.login(..))")
public void loginPointcut() {}
@AfterReturning(pointcut = "loginPointcut()", returning = "result")
public void logLoginSuccess(JoinPoint joinPoint, Object result) {
Object[] args = joinPoint.getArgs();
String username = (String) args[0];
logger.info("用户 {} 登录成功,时间:{}", username, new Date());
}
@AfterThrowing(pointcut = "loginPointcut()", throwing = "ex")
public void logLoginFailure(JoinPoint joinPoint, Exception ex) {
Object[] args = joinPoint.getArgs();
String username = (String) args[0];
logger.warn("用户 {} 登录失败,原因:{}", username, ex.getMessage());
}
}

<aop:config>
<aop:aspect id="logAspect" ref="loginLogAspect">
<aop:pointcut id="loginPointcut"
expression="execution(* com.javayouxue.service.UserService.login(..))"/>
<aop:after-returning method="logLoginSuccess"
pointcut-ref="loginPointcut" returning="result"/>
<aop:after-throwing method="logLoginFailure"
pointcut-ref="loginPointcut" throwing="ex"/>
</aop:aspect>
</aop:config>

@Aspect @Component public class PerformanceMonitorAspect {
private static final Logger logger = LoggerFactory.getLogger(PerformanceMonitorAspect.class);
@Around("execution(* com.javayouxue.service..*(..))")
public Object monitorPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
String methodName = joinPoint.getSignature().getName();
try {
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - startTime;
if (elapsedTime > 1000) {
logger.warn("方法 {} 执行耗时: {}ms", methodName, elapsedTime);
} else {
logger.debug("方法 {} 执行耗时: {}ms", methodName, elapsedTime);
}
return result;
} catch (Exception e) {
logger.error("方法 {} 执行异常: {}", methodName, e.getMessage());
throw e;
}
}
}

@Aspect @Component public class AdvancedPointcutAspect {
// 匹配Service层的方法,但不包括get开头的方法
@Pointcut("execution(* com.javayouxue.service..*(..)) && !execution(* com.javayouxue.service..*.get*(..))")
public void serviceMethodsExcludeGetters() {}
// 匹配带有特定注解的方法
@Pointcut("@annotation(com.javayouxue.annotation.BusinessLog)")
public void businessLogMethods() {}
// 组合切点:Service层方法且带有业务日志注解
@Pointcut("serviceMethodsExcludeGetters() && businessLogMethods()")
public void businessLogServiceMethods() {}
@Before("businessLogServiceMethods()")
public void logBusinessOperation(JoinPoint joinPoint) {
// 业务日志处理逻辑
}
}
// 强制使用CGLIB代理 @Configuration @EnableAspectJAutoProxy(proxyTargetClass = true) public class AopConfig {
// 这样配置后,即使目标类实现了接口,也会使用CGLIB代理
}
你可能想看:
Java优学网Spring AOP应用解析:轻松实现日志、权限、事务与性能监控
Java优学网Spring注解短文:掌握@Component、@Service、@Aspect等核心注解,轻松实现依赖注入与AOP切面编程
Java优学网Spring AOP讲解:告别重复代码,轻松实现日志与权限管理
Java优学网缓冲流入门解析:告别文件读写卡顿,5倍性能提升轻松实现
Java优学网线程池入门解析:从零掌握高效并发编程,轻松解决系统崩溃与性能瓶颈
Java优学网Spring AOP通知教程:轻松掌握五种通知类型,告别代码重复与维护难题