在Spring MVC中使用AOP需要先定義切面(Aspect),然后將切面織入到需要增強的目標方法中。
@Aspect
@Component
public class LogAspect {
@Before("execution(* com.example.controller.*.*(..))")
public void beforeMethod(JoinPoint joinPoint) {
System.out.println("Before executing method: " + joinPoint.getSignature());
}
@AfterReturning("execution(* com.example.controller.*.*(..))")
public void afterReturningMethod(JoinPoint joinPoint) {
System.out.println("After returning from method: " + joinPoint.getSignature());
}
}
<context:component-scan base-package="com.example.aspect" />
<aop:aspectj-autoproxy />
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user/{id}")
@ResponseBody
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@LogAspect
@RequestMapping("/user/save")
@ResponseBody
public String saveUser(@RequestBody User user) {
userService.saveUser(user);
return "User saved successfully";
}
}
通過以上步驟,就可以在Spring MVC中使用AOP實現日志記錄、權限控制等功能。需要注意的是,AOP僅能作用于Spring容器管理的Bean,因此需要將切面類和目標類都交由Spring容器管理。