【发布时间】:2019-11-07 19:47:24
【问题描述】:
我使用 Spring Boot 2.1.6.RELEASE 在 Spring 中创建了一个简单的切面。 它基本上记录了花费在方法上的总时间。
@Aspect
@Component
public class TimeLoggerAspect {
private static final Logger log = LoggerFactory.getLogger(TimeLoggerAspect.class);
@Around("@annotation(demo.TimeLogger)")
public Object methodTimeLogger(ProceedingJoinPoint joinPoint)
throws Throwable {
long startTime = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long totalTime = System.currentTimeMillis() - startTime;
log.info("Method " + joinPoint.getSignature() + ": " + totalTime + "ms");
return proceed;
}
}
切面由TimeLogger 注解触发
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimeLogger {
}
并且在这样的组件中使用
@Component
public class DemoComponent {
@TimeLogger
public void sayHello() {
System.out.println("hello");
}
}
Spring Boot 演示应用程序将通过CommandLineRunner 接口的run 方法调用sayHello。
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private DemoComponent demoComponent;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
demoComponent.sayHello();
}
}
为了完整起见,我在build.gradle 中添加了我的修改:为 aop、spring 测试和 jupiter (junit) 添加库。
compile("org.springframework.boot:spring-boot-starter-aop")
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("org.junit.jupiter:junit-jupiter-api")
testRuntime("org.junit.jupiter:junit-jupiter-engine")
运行应用程序将输出(为便于阅读而修剪)
hello
... TimeLoggerAspect : Method void demo.DemoComponent.sayHello(): 4ms
到目前为止,一切都很好。现在我基于@SpringBootTest注解和jupiter创建一个测试。
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {DemoComponent.class, TimeLoggerAspect.class})
public class DemoComponentFailTest {
@Autowired
private DemoComponent demoComponent;
@Test
public void shouldLogMethodTiming() {
demoComponent.sayHello();
}
}
在这里我得到了输出
hello
TimeLoggerAspect 没有输出,因为它似乎没有被触发。
是否缺少某些东西来触发测试中的方面?还是有其他方法可以在spring boot中测试方面?
【问题讨论】:
-
在一些相关的说明中,您是否查看过 Spring PerformanceMonitorInterceptor,它似乎已经完成了您尝试实施的工作?
-
否则,您是否尝试过使用
@SpringBootTest而不将其限制为特定的类? -
K.实际情况有点困难,所以我用它作为例子。删除注释上的“类”没有帮助。
标签: java spring-boot aop aspectj