首先一个springboot项目需要一个带main方法的类,然后这个类需要注解,还需要继承
@SpringBootApplication
public class ApplicationMain implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ApplicationMain.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("run...");
}
}
其次定义aspect要注意注解的使用
@Aspect
@Component
public class Aspect1 {
@Pointcut("@annotation(com.dick.job.annotation.Annotation1)")
public void pointcut1() {
}
@AfterReturning(returning = "result", value = "pointcut1()")
public void aspectFunction1(JoinPoint joinPoint, Object result) throws Throwable {
System.out.println("返回值:" + result);
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
System.out.println(className + " " + methodName);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Annotation1 annotation1 = method.getAnnotation(Annotation1.class);
System.out.println(annotation1.idName());
for (Object arg : joinPoint.getArgs()) {
System.out.println("args: " + arg);
}
}
@Around("@annotation(com.dick.job.annotation.Annotation1)")
public String aroundFunction(ProceedingJoinPoint joinPoint) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = joinPoint.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
System.out.println(time);
return result.toString() + time;
}
}
还有test的使用,
package com.dick.job; //test/java目录下的包结构要和main/java目录下的包结构一样
@SpringBootTest
public class utilTest {
@Autowired
Class1 class1;
@Test
public void test1() {
class1.testFunction1("dic", "pus", 3);
}
}
上面的问题花了我一天,百度太难用了,浪费生命
给你看看测试函数
@Component
@Log4j2
public class Class1 {
@Annotation1(idName = "testFunction1")
public String testFunction1(String a, String b, int c) {
log.trace("dick...");
for (int i=0; i<c; i++) {
System.out.println(a + " " + b);
}
return "asldkasdfasdlkfjas;ldkjfalsdjf;lasjfdlkasjf";
}
}
和annotation定义
package com.dick.job.annotation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Annotation1 {
String idName() default "id1";
}
结果
**
2021-10-29 16:12:01.550 [main] TRACE com.dick.job.utils.Class1 - dick…
dic pus
dic pus
dic pus
9
返回值:asldkasdfasdlkfjas;ldkjfalsdjf;lasjfdlkasjf9
com.dick.job.utils.Class1 testFunction1
testFunction1
args: dic
args: pus
args: 3
**