- 引入依赖
<!--面向切面-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
- LogAspect类
@Configuration
@Aspect
@Slf4j
public class LogAspect {
@Autowired
private LogService logService;
@Resource
HttpSession session;
@Around("@annotation(com.xiaozhi.annotation.AddLog)")
public Object addLog(ProceedingJoinPoint proceedingJoinPoint){
log.info("--环绕通知");
User user = (User) session.getAttribute("user");
MethodSignature methodSignature= (MethodSignature) proceedingJoinPoint.getSignature();
Method method = methodSignature.getMethod();
AddLog addLog = method.getAnnotation(AddLog.class);
String value = addLog.value();
String name = proceedingJoinPoint.getSignature().getName();
Object methodResult=null;
try{
methodResult = proceedingJoinPoint.proceed();
String message = "success";
Log logs = new Log(UUID.randomUUID().toString(), user.getUsername(), new Date(),value + "(" + name + ")", message);
logService.insert(logs);
log.info("日志入库"+logs);
}catch (Throwable throwable){
throwable.printStackTrace();
String message = "error";
}
return methodResult;
}
}
- AddLog annotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AddLog {
String value();
String name() default "";
}
- 根据注解使用代理
@AddLog(value = "修改用户")
@Override
public User update(User user) {
this.userDao.update(user);
return this.queryById(user.getId());
}