栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot aop

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot aop

首先一个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 

和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
**

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/358379.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号