nee*_*tno 5 benchmarking spring microbenchmark maven jmh
我尝试对我的 Spring(使用 maven)项目的一些方法进行基准测试。我需要在我的项目中的几个字段上使用 @Autowired 和 @Inject。当我运行我的项目时,它运行良好。但是 JMH 总是使用 @Autowired/@Inject 字段获取 NullPointerException。
public class Resources {
private List<Migratable> resources;
@Autowired
public void setResources(List<Migratable> migratables) {
this.resources = migratables;
}
public Collection<Migratable> getResources() {
return resources;
}
}
Run Code Online (Sandbox Code Playgroud)
我的基准课程
@State(Scope.Thread)
public class MyBenchmark {
@State(Scope.Thread)
public static class BenchmarkState {
Resources res;
@Setup
public void prepare() {
res = new Resources();
}
}
@Benchmark
public void testBenchmark(BenchmarkState state, Blackhole blackhole) {
blackhole.consume(state.res.getResources());
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的基准测试时,它在Resources.getResources()
更具体地说是在resources.
它不能自动装配 setResources()。但是如果我运行我的项目(排除基准),它工作正常。
在进行基准测试时,如何使用 Autowired 字段摆脱此 NullPointerException?
xwa*_*ndi -1
尝试使用
@RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(locations = {...})在测试课上。这应该初始化 Spring TestContext Framework 并让您自动装配依赖项。
如果这不起作用,那么您必须显式启动 Spring ApplicationContext 作为@Setup注解方法的一部分,使用以下任一方法
ClassPathXmlApplicationContext、FileSystemXmlApplicationContext 或 WebXmlApplicationContext 并从该上下文解析 bean:
ApplicationContext context = new ChosenApplicationContext("path_to_your_context_location");
res = context.getBean(Resources.class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
795 次 |
| 最近记录: |