AOP 没有命中自定义注解

问题描述 投票:0回答:1

我基本上试图创建一个注释,为我提供任何方法的执行时间。运行以下代码时,我不确定它是否命中了该方法。另外,intelliJ 建议“建议不建议任何方法”。

这就是我想要它做的 -


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
@ConditionalOnExpression("${aspect.enabled:true}")
public class ExecutionTimeTracker {
    @Around(value = "@annotation(TrackExecutionTime)")
    public Object executionTime(ProceedingJoinPoint point) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object object = point.proceed();
        long endtime = System.currentTimeMillis();
        log.info(point.getSignature().getDeclaringTypeName() +
                "." + point.getSignature().getName() +
                " >> Took : " + (endtime - startTime) + "mills");
        return object;
    }

}

这是我的@界面


import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ METHOD })
@Retention(RUNTIME)
public @interface TrackExecutionTime {
}

这是测试这个的UT -

import org.junit.jupiter.api.Test;

public class ExecutionTimeTrackerTest {

    @Test
    @TrackExecutionTime
    public void someMethod(){
        int[] randomNumbers = {582, 15, 596, 827, 779, 426, 153, 557, 394, 12};
        Arrays.sort(randomNumbers);
        int index = Arrays.binarySearch(randomNumbers, 827);
        Assertions.assertEquals(9, index);

    }
}

我尝试将 @Around(value = "@annotation(TrackExecutionTime)") 更改为不同的位置,也尝试设置不同的日志级别来执行。似乎没什么作用。

java spring spring-boot annotations spring-aop
1个回答
0
投票

问题在于该方面是由 Spring 管理的,而您在测试中没有使用 Spring。您需要创建一个 Spring Boot 集成测试才能使其工作。

示例:假设您有这项服务

@Service
class MyService {
    @TrackExecutionTime
    public void doSomething() {
        // just waste some time pretending to do something useful
        for (int i = 0; i < 100_000; i++) {
            Math.sqrt(1000);
        }
        System.out.println("Hello, world");
    }
}

然后你需要以下集成测试(老实说,这是一个毫无意义的测试,但这只是为了向你展示它是如何工作的):

@SpringBootTest
@RunWith(SpringRunner.class)
public class IntegrationTest {

    @Autowired
    MyService myService;

    @Test
    public void testAspect() {
        
        myService.doSomething();
    }
}

然后你会看到控制台中使用了该方面:

Hello, world
com.example.MyService.doSomething >> Took : 31mills
© www.soinside.com 2019 - 2024. All rights reserved.