|
AOP(面向切面编程)是一种编程思想,它可以将横切关注点(如日志、事务管理等)与核心业务逻辑分离开来,从而提高代码的可维护性和复用性。下面是几个常见的Java代码示例:
1. 日志记录:
```java
@Aspect
@Component
public class LoggingAspect {
@Pointcut("execution(* com.example.service.*.*(..))")
private void serviceMethods() {}
@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
System.out.println("正在执行方法: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "serviceMethods()", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("方法执行完成: " + joinPoint.getSignature().getName() + ",返回值为:" + result);
}
@AfterThrowing(pointcut = "serviceMethods()", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Exception exception) {
System.out.println("方法执行异常: " + joinPoint.getSignature().getName() + ",异常信息为:" + exception.getMessage());
}
}
```
2. 安全验证:
```java
@Aspect
@Component
public class SecurityAspect {
@Around("@annotation(com.example.annotations.RequiresPermission)")
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
// 执行权限验证逻辑...
if (hasPermission()) {
return joinPoint.proceed();
} else {
throw new SecurityException("无权限访问该资源");
}
}
private boolean hasPermission() {
// 权限验证逻辑...
return true;
}
}
```
3. 事务管理:
```java
@Aspect
@Component
public class TransactionAspect {
@Autowired
private PlatformTransactionManager transactionManager;
@Pointcut("@annotation(org.springframework.transaction.annotation.Transactional)")
private void transactionalMethods() {}
@Around("transactionalMethods()")
public Object manageTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
Object result = joinPoint.proceed();
transactionManager.commit(status);
return result;
} catch (Exception e) {
transactionManager.rollback(status);
throw e;
}
}
}
```
请注意,这些示例只是展示了AOP的一些用例,实际应用中可能需要根据具体业务场景进行更加精细的切面定义和逻辑处理。
|
|