用Spring AOP技术实现对用户的删除,添加,修改,查询操作按如下格式,[调用的那个类,哪个方法,调用时间,执行的操作(增,删,改,查)]等信息,通过java的io操作实现将日志记录在log.txt文件中
时间: 2023-05-12 10:05:13 浏览: 38
可以使用如下代码实现:
```java
@Aspect
@Component
public class UserAspect {
private static final Logger logger = LoggerFactory.getLogger(UserAspect.class);
@Pointcut("execution(* com.example.UserService.addUser(..))")
public void addUser() {}
@Pointcut("execution(* com.example.UserService.deleteUser(..))")
public void deleteUser() {}
@Pointcut("execution(* com.example.UserService.updateUser(..))")
public void updateUser() {}
@Pointcut("execution(* com.example.UserService.getUser(..))")
public void getUser() {}
@Before("addUser() || deleteUser() || updateUser() || getUser()")
public void logBefore(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
String operation = "";
if (methodName.startsWith("add")) {
operation = "增加";
} else if (methodName.startsWith("delete")) {
operation = "删除";
} else if (methodName.startsWith("update")) {
operation = "修改";
} else if (methodName.startsWith("get")) {
operation = "查询";
}
String log = String.format("%s类的%s方法在%s时进行了%s操作", className, methodName, new Date(), operation);
logger.info(log);
try {
FileWriter writer = new FileWriter("log.txt", true);
writer.write(log + "\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码使用了 Spring AOP 技术,在 UserService 的 addUser、deleteUser、updateUser 和 getUser 方法执行前,会先执行 logBefore 方法,将操作信息记录在日志文件 log.txt 中。