1
我们假设我想为该类编写一个benchmark
,该类可以是autowired
,因此我需要加载application context
。通过基准中的注释加载应用上下文
我的测试有注释@org.openjdk.jmh.annotations.State(Scope.Benchmark)
和主要方法
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(MyBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
当然,我有一些基准这样的:
@Benchmark
public void countAllObjects() {
Assert.assertEquals(OBJECT_COUNT, myAutowiredService.count());
}
现在的问题是我怎么注入myAutowiredService
?
可能的解决方法
负载手动@Setup
方法的上下文。
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/application-context.xml");
context.getAutowireCapableBeanFactory().autowireBean(this);
但我不喜欢这个解决方案。我宁愿我的测试只需要批注
@ContextConfiguration(locations = { "classpath:META-INF/application-context.xml" })
,然后我就注入我的豆状
@Autowired
private MyAutowiredService myAutowiredService;
但这不起作用。究其原因,我想,是我有没有注解我的测试应春润:
@RunWith(SpringJUnit4ClassRunner.class)
但是没有这样做,因为我还没有任何@Test
注解的方法的点,从而我会得到No runnable methods
异常。
在这种情况下,我可以通过注释加载上下文吗?
现在我仍然有基于XML的配置,但我想,有一天我会移动到基于注解版本。所以,根据你的回答,似乎不可能通过注释来做到,这是否正确? – Rufi
我没有测试过这个,但是如果你使用指向XML文件的@ContextConfiguration注释MyBenchmark类,AnnotationConfigWebApplicationContext方法应该可以工作。 –