Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

multithreading - Using @EnableAsync in Java Spring annotation sets the class levels instances as null

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...