2017-05-04 4 views
0

私はSpring(maven)プロジェクトのいくつかの方法をベンチマークしようとしています。プロジェクトのいくつかのフィールドで@Autowiredと@Injectを使う必要があります。プロジェクトを実行している間はうまくいきます。しかし、JMHは常に@ Autowired/@ InjectフィールドでNullPointerExceptionを取得します。JMH BenchmarkはSpring(Mavenを含む)プロジェクトのAutowiredフィールドでNullPointerExceptionを取得します

public class Resources { 

    private List<Migratable> resources; 

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

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

マイベンチマーククラス

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

私は私のベンチマークを実行すると、それは具体的にresourcesResources.getResources() でNullPointerExceptionが得られます。
setResources()をオートワイヤできません。しかし、私は私のプロジェクト(ベンチマークを除く)を実行する場合、それは正常に動作します。
ベンチマーク中にAutowiredフィールドでこのNullPointerExceptionを取り除くにはどうすればよいですか?

答えて

0

は、テストクラスに

@RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(locations = {...})を使用してみてください。これにより、Spring TestContext Frameworkが初期化され、依存関係が自動生成されます。

これが動作しない場合、あなたはあなたの一部として明示的に

ClassPathXmlApplicationContext、FileSystemXmlApplicationContextまたは WebXmlApplicationContextのいずれかを使用して@Setupアノテーション付きメソッドを、春のApplicationContextを起動してから豆を解決する必要がそのコンテキスト:

ApplicationContext context = new ChosenApplicationContext("path_to_your_context_location"); 
res = context.getBean(Resources.class); 
関連する問題