JMH基准测试在Spring中使用Autowired字段获取NullPointerException(使用maven)项目

问题描述:

我尝试对我的Spring(使用maven)项目的一些方法进行基准测试。我需要在我的项目的几个字段中使用@Autowired和@Inject。当我运行我的项目时,它运行良好。但JMH总是通过@ Autowired/@ Inject字段获得NullPointerException。JMH基准测试在Spring中使用Autowired字段获取NullPointerException(使用maven)项目

public class Resources { 

    private List<Migratable> resources; 

    @Autowired 
    public void setResources(List<Migratable> migratables) { 
     this.resources = migratables; 
    } 

    public Collection<Migratable> getResources() { 
     return resources; 
    } 
} 

我的Benchmark类

@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()); 
    } 
} 

当我运行我的基准,它在Resources.getResources() 得到NullPointerException异常更具体地说,在resources
它不能Autowire setResources()。但是如果我运行我的项目(排除基准),它工作正常。
如何在基准测试中摆脱带有Autowired字段的NullPointerException?

尝试在测试类使用

@RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(locations = {...})。这应该初始化Spring TestContext框架并允许自动装配依赖关系。

如果这不工作,那么你必须明确地启动Spring的ApplicationContext作为你@Setup批注的方法的一部分,无论是使用的

的ClassPathXmlApplicationContext,FileSystemXmlApplicationContext来或 WebXmlApplicationContext和解决豆类该背景:

ApplicationContext context = new ChosenApplicationContext("path_to_your_context_location"); 
res = context.getBean(Resources.class);