跳到主要内容

钩子

一、事件监听

// 定义订单创建事件
public class OrderCreatedEvent extends ApplicationEvent {
public OrderCreatedEvent(Object source) {
super(source);
}
}

// 监听订单创建事件的监听器
@Component
public class OrderCreatedEventListener implements ApplicationListener<OrderCreatedEvent> {
@Override
public void onApplicationEvent(OrderCreatedEvent event) {
// 在这里执行订单创建后的逻辑
System.out.println("Order Created Event Received. Processing...");
}
}

// 触发订单创建事件的业务逻辑
@Service
public class OrderService {
@Autowired
private ApplicationEventPublisher eventPublisher;

public void createOrder() {
// 创建订单的业务逻辑...

// 发布订单创建事件
eventPublisher.publishEvent(new OrderCreatedEvent(this));
}
}

二、拦截器

public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在这里执行权限验证逻辑
if (/* 用户没有权限 */) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
return false;
}
return true;
}
}

// 配置拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private AuthInterceptor authInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor);
}
}

三、切面

@Aspect
@Component
public class LoggingAspect {

@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethodExecution(JoinPoint joinPoint) {
// 在方法执行前记录日志
System.out.println("Method execution started: " + joinPoint.getSignature().toShortString());
}

@After("execution(* com.example.service.*.*(..))")
public void logAfterMethodExecution(JoinPoint joinPoint) {
// 在方法执行后记录日志
System.out.println("Method execution completed: " + joinPoint.getSignature().toShortString());
}
}