我使用下面的代码来测试我的异步实现。 (参考另一篇SO帖子https://stackoverflow.com/a/20807233/1989988)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyAsyncClassTest {
@Configuration
@EnableAsync
static class Config {
@Bean
public MyAsyncClass myAsyncClass() {
Parameter1 param1 = new Parameter1();
Parameter2 param2 = new Parameter2();
return new MyAsyncClass(param1, param2);
}
}
@Autowired
private MyAsyncClass myAsyncClass;
@Test
public void test() throws Exception {
myAsyncClass //it has param1 and param2 set as null
//if @EnableAsync is removed, then param1 and param2 are set but async call is not working
}
编辑:"这里MyAsyncClass是一个有一些使用Spring的@Async注释注释的方法的类。"
正如代码注释中所提到的,在使用null
注释时,我在测试方法中将类级别字段设置为@EnableAsync
,并且在调试时显示了很多cglib$Callback
个字段。
修改
主类:
@Component
public class MyAsyncClass {
private final Param1 param1;
private final Param2 param2;
@Autowired
public MyAsyncClass(final Param1 param1, final Param2 param2) {
this.param1 = param1;
this.param2 = param2;
}
@Async
public Future<T> performAction() {
String result = param1.getDefaultName() + param2.getDefaultName();
return new AsyncResult<String>(result);
}
@Async
public Future<String> performAnotherAction() {
String result = param1.getDefaultName() + param2.getDefaultName();
return new AsyncResult<String>(result);
}
}
类Param1和Param2:
@Component
public class Param1 {
public String getDefaultName() {
return "Param1";
}
}
@Component
public class Param2 {
public String getDefaultName() {
return "Param2";
}
}