Hello. Can I declare suspending methods in Spring ...
# spring
r
Hello. Can I declare suspending methods in Spring components in the current Spring Boot version (2.1.6)?
s
No, only in Spring Boot 2.2 with WebFlux
r
And in 2.2 but without webflux I can't?
s
Nope, Coroutines support is built on top of WebFlux, see https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow for more details.
r
I'm using 2.1.6 with some non-typical configuration (SOAP services with Apache CXF). I've tested coroutines and they seem to work for me. So I'm puzzled.
how can it work? 🙂
I've created a component like this:
Copy code
@Service
class DokumentService {

    suspend fun test() {
        println("pre test")
        delay(5000)
        println("post test")
    }
}
s
Where/how are you using this service ?
r
And I have a web service component (initialized by CXF):
Copy code
@Service
@WebService(...)
class PeupImpl(
    private val dokumentService: DokumentService
) : Peup, CoroutineScope by CoroutineScope(Dispatchers.Default) {

    override fun oczekujaceDokumentyAsync(
        request: OczekujaceDokumentyRequestType,
        asyncHandler: AsyncHandler<OczekujaceDokumentyResponseType>
    ): Future<*> {
        return asyncWS(asyncHandler) {
            dokumentService.test()
            delay(10000)
            OczekujaceDokumentyResponseType().apply { liczba = 2 }
        }
    }

}
asyncWs is a helper extension function:
Copy code
fun <T> CoroutineScope.asyncWS(asyncHandler: AsyncHandler<T>, block: suspend () -> T): ServerAsyncResponse<T> {
    val result = ServerAsyncResponse<T>()
    launch {
        val v = block()
        result.set(v)
        asyncHandler.handleResponse(result)
    }
    return result
}
This is just some of my testing, to find out if I can use coroutines for soap web services. It seems to work, but I'm not sure if I'm not missing something about Spring Boot.
a service should be a proxy, right?
is it just proxying suspending function?
s
Service does not imply proxy
Here you are not using any kind of Coroutines support from Spring since you are creating the coroutines scope yourself
I have not tried this kind of construct
r
when a service is injected as a proxy and when it's not?
s
It depends if you need transactions, security, etc.
Spring Boot 2.1 has 0 support for Coroutines so pretty sure that will fail for some use cases
r
And what is the state of 2.2? When it will be production ready?
Currently
CoroutineScope by CoroutineScope
usage pattern is not actively supported to feel free to create an issue at Spring Framework level if you see some issues.
r
ok, thx for help! 🙂
👍 1