不使用aop可以实现自定义日志记录注解吗
时间: 2023-12-10 16:02:20 浏览: 82
是的,可以通过自定义注解和编写拦截器来实现自定义日志记录。具体步骤如下:
1. 定义注解
```java
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
```
2. 编写拦截器
```java
@Component
@Aspect
public class LogAspect {
@Autowired
private LogService logService;
@Pointcut("@annotation(com.example.demo.annotation.Log)")
public void logPointCut() {
}
@Before("logPointCut()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log logAnnotation = method.getAnnotation(Log.class);
String description = logAnnotation.value();
String methodName = signature.getName();
String className = joinPoint.getTarget().getClass().getName();
String params = Arrays.toString(joinPoint.getArgs());
logService.saveLog(className, methodName, params, description);
}
}
```
3. 在需要记录日志的方法上使用注解
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/users")
@Log("添加用户")
public Result addUser(@RequestBody User user) {
userService.addUser(user);
return Result.success();
}
}
```
这样,在调用 `addUser` 方法时就会触发拦截器,从而实现自定义日志记录。
阅读全文