我使用 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 演示应用程序将调用sayHello
通过run
的方法CommandLineRunner
界面。
@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 test 和 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
注释和木星。
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 中的方面吗?