在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容器管理。