简体   繁体   中英

Using SpringFrameWork @Async for methods that return void

I'm using the Spring Boot framework as my backend.

This is one of the calls I want to do asynchronously - it just saves a user into my mongoDB database:

@Async
public Future<Void> saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    return new AsyncResult<Void>(mongoTemplate.save(user));
}

The method gives me an errors as mongoTemplate.save(user) returns a void value and not a Void object.

I tried to change the method by substituting in void as follows but it does not work as Future<void> and AsyncResult<void> is not accepted:

@Async
public Future<void> saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    return new AsyncResult<void>(mongoTemplate.save(user));
}

Is there anyway to run a method that returns void in an asynchronous way on Spring?

Try the following:

@Async
public void saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    mongoTemplate.save(user);
}

Future needs to be used only when there is return type other than void.

The only value a Void can have is null . So all you need is

User user = new User();
user.setUserId(userid);
mongoTemplate.save(user)
return new AsyncResult<Void>(null);

简单返回

return new AsyncResult<>(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM