用Spring AOP技术实现对用户的删除,添加,修改,查询操作按如下格式,[调用的那个类,哪个方法,调用时间,执行的操作(增,删,改,查)]等信息,通过java的io操作实现将日志记录在log.txt文件中
时间: 2023-05-11 16:05:53 浏览: 68
可以使用Spring AOP的@Aspect注解和@Around注解来实现对用户的删除、添加、修改、查询操作的日志记录。具体实现步骤如下:
1. 创建一个切面类,使用@Aspect注解标注,同时在类中定义一个方法,使用@Around注解标注,该方法用于拦截被@Log注解标注的方法。
2. 在该方法中,使用JoinPoint对象获取被拦截方法的相关信息,包括调用的类、方法名、参数等。
3. 根据获取到的信息,将日志信息格式化成指定的格式,例如"[调用的类,哪个方法,调用时间,执行的操作(增,删,改,查)]"。
4. 使用Java的IO操作将日志信息写入到log.txt文件中。
下面是一个示例代码:
```java
@Aspect
@Component
public class LogAspect {
@Around("@annotation(com.example.demo.annotation.Log)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取被拦截方法的相关信息
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
String operation = "";
if (methodName.startsWith("add")) {
operation = "增加";
} else if (methodName.startsWith("delete")) {
operation = "删除";
} else if (methodName.startsWith("update")) {
operation = "修改";
} else if (methodName.startsWith("query")) {
operation = "查询";
}
String logInfo = String.format("[%s,%s,%s,%s]", className, methodName, new Date(), operation);
// 写入日志文件
FileWriter writer = new FileWriter("log.txt", true);
writer.write(logInfo + "\n");
writer.flush();
writer.close();
// 执行被拦截方法
return joinPoint.proceed(args);
}
}
```
在需要记录日志的方法上使用@Log注解即可,例如:
```java
@Log
public void addUser(User user) {
// 添加用户的业务逻辑
}
```
这样,每次调用addUser方法时,都会自动记录一条日志到log.txt文件中。