盒子
盒子
文章目录
  1. 功能说明
  2. 依赖
  3. 定义注解
  4. 实现对自定义注解的aop
  5. 模拟业务
  6. 测试
  7. 结果

简单日志aop和注解实现

前沿: 对于日志的aop可以不用自定义注解,但是为了爽一把自定义注解和aop,所以这里做了一个简单的demo

功能说明

在使用了自定义的注解的方法上,如果被调用则,会输出该方法的描述和执行时间

依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

定义注解

1
2
3
4
5
6
7
8
9
/**
* @author GXM www.guokangjie.cn
* @date 2019/8/30
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RecordTime {
String description() default "";
}

实现对自定义注解的aop

主要就是把以前的execution表达式改为注解

@Pointcut(“execution( com.loongshawn.method.ces...*(..))”)

改为

@Pointcut(“@annotation(recordTime)”)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Aspect
@Component
@Slf4j
public class LogAspect {

/**
* 切点
* @param recordTime
*/
@Pointcut("@annotation(recordTime)")
public void dealTime(RecordTime recordTime) {}


@Before("dealTime(recordTime)")
public void doBefore(JoinPoint joinPoint, RecordTime recordTime) {
// 记录请求到达时间
log.info("description:{}", recordTime.description());
}

@After("dealTime(recordTime)")
public void doAfter(RecordTime recordTime) {
log.info("endTime:{}, description:{}", formatDate(new Date()), recordTime.description());
}


public String formatDate(Date date){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(date);
}
}

模拟业务

假如我想知道每次都是什么时间我的fillMoney方法被调用,都是什么时间点冲的钱

1
2
3
4
5
6
7
8
@Service
public class OnlineService {

@RecordTime(description = "fillMoney方法被调用")
public String fillMoney() {
return "ok";
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
@SpringBootTest
@RunWith(SpringRunner.class)
public class AopTest {
@Autowired
private OnlineService onlineService;

@Test
public void test(){
onlineService.fillMoney();
}
}

结果

控制台就会显示日志了

1
2
description:getAllUser方法被调用
endTime:2019-08-30 14:43:39, description:getAllUser方法被调用

希望对您有所帮助
May all the ordinary are great, all the ignoble bloom
  • smile