Skip to content

Commit

Permalink
Throw an exception for suspending factory methods
Browse files Browse the repository at this point in the history
Suspending factory methods are not supported, and can
have side effects, so it is better to fail explicitly
for such use case.

Closes spring-projectsgh-32719
  • Loading branch information
sdeleuze committed May 10, 2024
1 parent a02861f commit 39dd9be
Show file tree
Hide file tree
Showing 9 changed files with 203 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public CodeBlock generateCode(RegisteredBean registeredBean, InstantiationDescri
if (constructorOrFactoryMethod instanceof Constructor<?> constructor) {
return generateCodeForConstructor(registeredBean, constructor);
}
if (constructorOrFactoryMethod instanceof Method method) {
if (constructorOrFactoryMethod instanceof Method method && !KotlinDetector.isSuspendingFunction(method)) {
return generateCodeForFactoryMethod(registeredBean, method, instantiationDescriptor.targetClass());
}
throw new IllegalStateException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.core.CollectionFactory;
import org.springframework.core.KotlinDetector;
import org.springframework.core.MethodParameter;
import org.springframework.core.NamedThreadLocal;
import org.springframework.core.ParameterNameDiscoverer;
Expand Down Expand Up @@ -623,6 +624,11 @@ else if (void.class == factoryMethodToUse.getReturnType()) {
"Invalid factory method '" + mbd.getFactoryMethodName() + "' on class [" +
factoryClass.getName() + "]: needs to have a non-void return type!");
}
else if (KotlinDetector.isKotlinPresent() && KotlinDetector.isSuspendingFunction(factoryMethodToUse)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Invalid factory method '" + mbd.getFactoryMethodName() + "' on class [" +
factoryClass.getName() + "]: suspending functions are not supported!");
}
else if (ambiguousFactoryMethods != null) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous factory method matches found on class [" + factoryClass.getName() + "] " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@ import org.junit.jupiter.api.Test
import org.springframework.aot.hint.*
import org.springframework.aot.test.generate.TestGenerationContext
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.beans.factory.support.DefaultListableBeanFactory
import org.springframework.beans.factory.support.InstanceSupplier
import org.springframework.beans.factory.support.RegisteredBean
import org.springframework.beans.factory.support.RootBeanDefinition
import org.springframework.beans.factory.support.*
import org.springframework.beans.testfixture.beans.KotlinConfiguration
import org.springframework.beans.testfixture.beans.KotlinTestBean
import org.springframework.beans.testfixture.beans.KotlinTestBeanWithOptionalParameter
import org.springframework.beans.testfixture.beans.factory.aot.DeferredTypeBuilder
import org.springframework.beans.testfixture.beans.factory.generator.SimpleConfiguration
import org.springframework.core.test.tools.Compiled
import org.springframework.core.test.tools.TestCompiler
import org.springframework.javapoet.MethodSpec
Expand All @@ -47,6 +46,8 @@ class InstanceSupplierCodeGeneratorKotlinTests {

private val generationContext = TestGenerationContext()

private val beanFactory = DefaultListableBeanFactory()

@Test
fun generateWhenHasDefaultConstructor() {
val beanDefinition: BeanDefinition = RootBeanDefinition(KotlinTestBean::class.java)
Expand Down Expand Up @@ -74,6 +75,41 @@ class InstanceSupplierCodeGeneratorKotlinTests {
.satisfies(hasMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
}

@Test
fun generateWhenHasFactoryMethodWithNoArg() {
val beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(String::class.java)
.setFactoryMethodOnBean("stringBean", "config").beanDefinition
this.beanFactory.registerBeanDefinition(
"config", BeanDefinitionBuilder
.genericBeanDefinition(KotlinConfiguration::class.java).beanDefinition
)
compile(beanFactory, beanDefinition) { instanceSupplier, compiled ->
val bean = getBean<String>(beanFactory, beanDefinition, instanceSupplier)
Assertions.assertThat(bean).isInstanceOf(String::class.java)
Assertions.assertThat(bean).isEqualTo("Hello")
Assertions.assertThat(compiled.sourceFile).contains(
"getBeanFactory().getBean(KotlinConfiguration.class).stringBean()"
)
}
Assertions.assertThat<TypeHint?>(getReflectionHints().getTypeHint(KotlinConfiguration::class.java))
.satisfies(hasMethodWithMode(ExecutableMode.INTROSPECT))
}

@Test
fun generateWhenHasSuspendingFactoryMethod() {
val beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(String::class.java)
.setFactoryMethodOnBean("suspendingStringBean", "config").beanDefinition
this.beanFactory.registerBeanDefinition(
"config", BeanDefinitionBuilder
.genericBeanDefinition(KotlinConfiguration::class.java).beanDefinition
)
Assertions.assertThatIllegalStateException().isThrownBy {
compile(beanFactory, beanDefinition) { _, _ -> }
}
}

private fun getReflectionHints(): ReflectionHints {
return generationContext.runtimeHints.reflection()
}
Expand All @@ -96,6 +132,14 @@ class InstanceSupplierCodeGeneratorKotlinTests {
}
}

private fun hasMethodWithMode(mode: ExecutableMode): ThrowingConsumer<TypeHint> {
return ThrowingConsumer { hint: TypeHint ->
Assertions.assertThat(
hint.methods()
).anySatisfy(hasMode(mode))
}
}

@Suppress("UNCHECKED_CAST")
private fun <T> getBean(beanFactory: DefaultListableBeanFactory, beanDefinition: BeanDefinition,
instanceSupplier: InstanceSupplier<*>): T {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.beans.factory.support

import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.springframework.beans.BeanWrapper
import org.springframework.beans.factory.BeanCreationException
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.beans.testfixture.beans.factory.generator.factory.KotlinFactory

class ConstructorResolverKotlinTests {

@Test
fun instantiateBeanInstanceWithBeanClassAndFactoryMethodName() {
val beanFactory = DefaultListableBeanFactory()
val beanDefinition: BeanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(KotlinFactory::class.java).setFactoryMethod("create")
.beanDefinition
val beanWrapper = instantiate(beanFactory, beanDefinition)
Assertions.assertThat(beanWrapper.wrappedInstance).isEqualTo("test")
}

@Test
fun instantiateBeanInstanceWithBeanClassAndSuspendingFactoryMethodName() {
val beanFactory = DefaultListableBeanFactory()
val beanDefinition: BeanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(KotlinFactory::class.java).setFactoryMethod("suspendingCreate")
.beanDefinition
Assertions.assertThatThrownBy { instantiate(beanFactory, beanDefinition, null) }
.isInstanceOf(BeanCreationException::class.java)
.hasMessageContaining("suspending functions are not supported")

}

private fun instantiate(beanFactory: DefaultListableBeanFactory, beanDefinition: BeanDefinition, vararg explicitArgs: Any?): BeanWrapper {
return ConstructorResolver(beanFactory)
.instantiateUsingFactoryMethod("testBean", (beanDefinition as RootBeanDefinition), explicitArgs)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.beans.testfixture.beans

class KotlinConfiguration {

fun stringBean(): String {
return "Hello"
}

suspend fun suspendingStringBean(): String {
return "Hello"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.beans.testfixture.beans.factory.generator.factory

class KotlinFactory {

companion object {

@JvmStatic
fun create() = "test"

@JvmStatic
suspend fun suspendingCreate() = "test"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ public String getParameterName() {
else if (this.executable instanceof Constructor<?> constructor) {
parameterNames = discoverer.getParameterNames(constructor);
}
if (parameterNames != null) {
if (parameterNames != null && this.parameterIndex < parameterNames.length) {
this.parameterName = parameterNames[this.parameterIndex];
}
this.parameterNameDiscoverer = null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -20,6 +20,7 @@ import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

import org.springframework.util.ReflectionUtils
import kotlin.coroutines.Continuation

/**
* Abstract tests for Kotlin [ParameterNameDiscoverer] aware implementations.
Expand All @@ -46,6 +47,13 @@ abstract class AbstractReflectionParameterNameDiscovererKotlinTests(protected va
assertThat(actualMethodParams).contains("message")
}

@Test
fun getParameterNamesOnSuspendingFunction() {
val method = ReflectionUtils.findMethod(CoroutinesMessageService::class.java, "sendMessage", String::class.java, Continuation::class.java)!!
val actualMethodParams = parameterNameDiscoverer.getParameterNames(method)
assertThat(actualMethodParams).containsExactly("message")
}

@Test
fun getParameterNamesOnExtensionMethod() {
val method = ReflectionUtils.findMethod(UtilityClass::class.java, "identity", String::class.java)!!
Expand All @@ -65,4 +73,8 @@ abstract class AbstractReflectionParameterNameDiscovererKotlinTests(protected va
fun String.identity() = this
}

class CoroutinesMessageService {
suspend fun sendMessage(message: String) = message
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,27 @@ class MethodParameterKotlinTests {
assertThat(returnGenericParameterType("suspendFun8")).isEqualTo(Object::class.java)
}

@Test
fun `Parameter name for regular function`() {
val methodParameter = returnMethodParameter("nullable", 0)
methodParameter.initParameterNameDiscovery(KotlinReflectionParameterNameDiscoverer())
assertThat(methodParameter.getParameterName()).isEqualTo("nullable")
}

@Test
fun `Parameter name for suspending function`() {
val methodParameter = returnMethodParameter("suspendFun", 0)
methodParameter.initParameterNameDiscovery(KotlinReflectionParameterNameDiscoverer())
assertThat(methodParameter.getParameterName()).isEqualTo("p1")
}

@Test
fun `Continuation parameter name for suspending function`() {
val methodParameter = returnMethodParameter("suspendFun", 1)
methodParameter.initParameterNameDiscovery(KotlinReflectionParameterNameDiscoverer())
assertThat(methodParameter.getParameterName()).isNull()
}

@Test
fun `Continuation parameter is optional`() {
val method = this::class.java.getDeclaredMethod("suspendFun", String::class.java, Continuation::class.java)
Expand All @@ -126,8 +147,8 @@ class MethodParameterKotlinTests {
private fun returnGenericParameterTypeName(funName: String) = returnGenericParameterType(funName).typeName
private fun returnGenericParameterTypeBoundName(funName: String) = (returnGenericParameterType(funName) as TypeVariable<*>).bounds[0].typeName

private fun returnMethodParameter(funName: String) =
MethodParameter(this::class.declaredFunctions.first { it.name == funName }.javaMethod!!, -1)
private fun returnMethodParameter(funName: String, parameterIndex: Int = -1) =
MethodParameter(this::class.declaredFunctions.first { it.name == funName }.javaMethod!!, parameterIndex)

@Suppress("unused_parameter")
fun nullable(nullable: String?): Int? = 42
Expand Down

0 comments on commit 39dd9be

Please sign in to comment.