志向是天才的幼苗,经过热爱劳动的双手培育,在肥田沃土里将成长为粗壮的大树。——苏霍姆林斯基

之前写过自定义注解和AOP,但其是作用于方法上

今天用kotlin写一个作用在类上的:主要是@annotation换成@within

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.ruben.simpleboot

import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController


@SpringBootApplication
class SimpleBootApplication

fun main(args: Array<String>) {
runApplication<SimpleBootApplication>(*args)
}

// 一个简单的Controller
@RestController
@TestInterface
class TestController {
@GetMapping("test")
fun test(): String {
return "test";
}

@GetMapping("mock")
fun mock(): String {
return "mock";
}
}

// 注解
annotation class TestInterface

// AOP
@Aspect
@Component
class TestAop {
// 针对注解目标的Class进行匹配
@Around("@within(TestInterface)")
fun recordWithMe(point: ProceedingJoinPoint): Any {
return point.proceed()
}
}

访问testmock接口均成功进入AOP逻辑

image-20220817170126372