Throw an exception for suspending factory methods

Suspending factory methods are not supported, and can
have side effects, so it is better to fail explicitly
for such use case.

Closes gh-32719
This commit is contained in:
Sébastien Deleuze
2024-05-10 11:45:24 +02:00
parent a02861f7db
commit 7985ab33f4
9 changed files with 200 additions and 9 deletions

View File

@@ -142,7 +142,7 @@ public class InstanceSupplierCodeGenerator {
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(

View File

@@ -63,6 +63,7 @@ import org.springframework.beans.factory.config.DependencyDescriptor;
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;
@@ -623,6 +624,11 @@ class ConstructorResolver {
"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() + "] " +

View File

@@ -22,10 +22,8 @@ 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
@@ -47,6 +45,8 @@ class InstanceSupplierCodeGeneratorKotlinTests {
private val generationContext = TestGenerationContext()
private val beanFactory = DefaultListableBeanFactory()
@Test
fun generateWhenHasDefaultConstructor() {
val beanDefinition: BeanDefinition = RootBeanDefinition(KotlinTestBean::class.java)
@@ -74,6 +74,39 @@ 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()
}
@@ -96,6 +129,12 @@ 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 {

View File

@@ -0,0 +1,55 @@
/*
* 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)
}
}

View File

@@ -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"
}
}

View File

@@ -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"
}
}