Spring Cloud 实体类 Set 方法日志记录实现:使用 AOP 技术
在 Spring Cloud 中,可以使用 AOP(面向切面编程)技术来实现对 set 方法的日志记录。具体实现步骤如下:
- 定义一个切面类,实现对 set 方法的日志记录:
@Aspect
@Component
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Pointcut('execution(* com.example.demo.entity.*.set*(..))')
public void setPointcut() {}
@Before('setPointcut()')
public void logBefore(JoinPoint joinPoint) {
logger.info('调用了 ' + joinPoint.getSignature().getName() + ' 方法,参数为:' + Arrays.toString(joinPoint.getArgs()));
}
}
上面的代码中,使用 @Aspect 注解标注该类为切面类;使用 @Pointcut 注解定义切点,这里定义了所有以“set”开头的方法;使用 @Before 注解定义前置通知,在调用 set 方法之前记录日志信息。
- 在 Spring Boot 应用程序中配置切面:
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
在 Spring Boot 应用程序的启动类上添加 @EnableAspectJAutoProxy 注解,开启自动代理。
完整的实现代码如下:
@Aspect
@Component
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Pointcut('execution(* com.example.demo.entity.*.set*(..))')
public void setPointcut() {}
@Before('setPointcut()')
public void logBefore(JoinPoint joinPoint) {
logger.info('调用了 ' + joinPoint.getSignature().getName() + ' 方法,参数为:' + Arrays.toString(joinPoint.getArgs()));
}
}
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
原文地址: https://www.cveoy.top/t/topic/nENn 著作权归作者所有。请勿转载和采集!