I am using below code to test my asynchronous implementation.
(reference from another SO post 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
}
Edit: "Here MyAsyncClass is a class having a few methods annotated with Spring's @Async annotation."
As mentioned in the code comments, I am getting the class level fields set as null
in my test method when using @EnableAsync
annotation and there are so many cglib$Callback
fields are shown at debug time.
Edit:
Main Class:
@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);
}
}
Classes Param1 and Param2 :
@Component
public class Param1 {
public String getDefaultName() {
return "Param1";
}
}
@Component
public class Param2 {
public String getDefaultName() {
return "Param2";
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…