我有一个现有的Springboot / Java应用程序,我想开始将应用程序迁移到Kotlin。我在Kotlin中创建一个@Service,我的单元测试在运行时失败,因为Spring无法找到我的服务。
我的单元测试:
@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = arrayOf(Application::class))
class Junit5SpringKotlinTests {
@Autowired // Springboot ConfigurationProperties (application.yaml) mapped to Java bean. This works.
lateinit var applicationConfigurationJavaBean: EnvironmentProperties
fun appProperties(): EnvironmentProperties.Environment? {
return applicationConfigurationJavaBean.environments[applicationConfigurationJavaBean.activeEnvironment]
}
@Autowired
lateinit var testServiceKotlinBean :TestService // My Kotlin @Service which can not be found at runtime.
@Test
fun `ApplicationConfiguration`() {
println(appProperties()?.baseClientId)
testServiceKotlinBean.hello()
}
}
我的Kotlin服务:TestService.kt
import org.springframework.stereotype.Service
@Service
class TestService {
fun hello() {
println("hello from service")
}
}
运行时执行单元测试的错误:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Junit5SpringKotlinTests': Unsatisfied dependency expressed through field 'testServiceKotlinBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'api.model.TestService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'api.model.TestService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
FWW,我能够在Kotlin测试代码中编写JUnit5 SpringBootTests并运用我所有的Java组件,因此这与Spring在运行时发现的Kotlin组件有关。 Java组件可以工作。
我怀疑这可能是构建问题并且已经看到类似的问题。我的pom.xml中包含以下内容:
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
</dependency>
所以这不是问题。
答案 0 :(得分:0)
问题是我用于Kotlin服务的包名。 Kotlin很好,因为我没有把我的文件放在像java这样的包路径中。但我的Spring类路径扫描依赖于一个包:A.B.C及以下,我的Kotlin路径只有C.我将我的Kotlin文件中的包名改为A.B.C.TestService,一切都很好。耶。