在实际的项目中对外暴露的接口通常需要打印请求日志,以下就是使用切面做一个请求日志打印的功能:
首先先导入AOP相关的包,SpringBoot的项目启动类需要添加@EnableAspectJAutoProxy 注解
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
注解类:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogParam {
}
切面类:
@Aspect
@Component
public class MethodLogParam {
private final Logger logger = LoggerFactory.getLogger(MethodLogParam.class);
@Pointcut("@annotation(com.term.spring_batch.annotation.LogParam)")
public void logPointCut() {
}
@Before("logPointCut()")
public void before(JoinPoint joinPoint) {
try {
String methodName = joinPoint.getSignature().getName();
logger.info("请求{}.{}入参日志:【{}】", joinPoint.getTarget().getClass(), methodName, joinPoint.getArgs());
} catch (Exception e) {
logger.error("入参日志打印异常", e);
}
}
}
目标类:
@Service
public class AopService {
private final Logger logger = LoggerFactory.getLogger(AopService.class);
@Autowired
private UserMapper userMapper;
// 在需要打印日志的方法上添加日志打印的注解
@LogParam
public int insertBatchData(List<User> userList) {
int count = 0;
for (User user : userList) {
try {
// 使用AOP的方式调用本类方法
count += ((AopService) AopContext.currentProxy()).insertOneData(user);
} catch (Exception e) {
// 发生异常只记录日志不阻断程序
logger.error("数据插入异常", e);
}
}
return count;
}
测试类:(随便写个Spring测试类或者启动项目测试都行)
@SpringBootTest
@RunWith(SpringRunner.class)
public class AopServiceTest {
@Autowired
private AopService aopService;
@Test
public void testInsertBatch() {
int result = aopService.insertBatchData(Arrays.asList(creatUser("张三"), creatUser("李四"), creatUser("王五")));
System.out.println("数据库更新的条目数为 "+result);
}
// 生成实体类对象
private User creatUser(String name) {
User user = new User();
user.setName(name);
user.setAge((int) (Math.random() * 80));
user.setEmail("[email protected]");
return user;
}
}
日志:
2021-11-28 18:32:17.719 INFO 3112 --- [ main] c.t.spring_batch.aspect.MethodLogParam : 请求class com.term.spring_batch.service.AopService.insertBatchData入参日志:【[[User{id=null, name='张三', age=64, email='[email protected]'}, User{id=null, name='李四', age=76, email='[email protected]'}, User{id=null, name='王五', age=56, email='[email protected]'}]]】
以上。