0

Because of some context requirement , I have to mark my spring bean context :

context(IConfig)
@Named
class MyService (...) {

   val config = SomeBuilder().build() // it needs IConfig context
}

And the test class :

internal class MyServiceTest : AbstractCoreTest()  {

  @Inject
  private lateinit var myService: MyService
  
  // do tests
}

It compiles OK , but when executing , it throws :

java.lang.IllegalStateException: Failed to load ApplicationContext
 for [MergedContextConfiguration@484876a1 testClass = 
foo.MyServiceTest, locations = ["classpath:core.xml"], 
classes = [], contextInitializerClasses = [destiny.TestAppInit], 
activeProfiles = [], propertySourceLocations = [], propertySourceProperties = [], 
contextCustomizers = [], contextLoader = 
org.springframework.test.context.support.DelegatingSmartContextLoader, parent = null]
    at 
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext
...
...
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error 
creating bean with name 'myService' defined in file [.../MyService.class]: Unsatisfied
 dependency expressed through constructor parameter 0: No qualifying bean of type 
'IConfig' available: expected at least 1 bean which qualifies as autowire candidate. 
Dependency annotations: {}

Is there a better way to solve this ? Thanks.

Kotlin 1.8.21 , Spring 6.0.9

smallufo
  • 11,516
  • 20
  • 73
  • 111
  • But who would provide `IConfig` instance ? If it is a Spring Bean, I do not see why Kotlin Context receiver is needed (a post-construct method receiving the IConfig instance should do). If it is not a bean, I do not see how Spring could prepare a kotlin context for this (it is not in its list of available components). – amanin Jun 30 '23 at 11:56
  • 1
    And now, I am starting to understand that kotlin context receiver might "just" add the IConfig object as constructor parameter under the hood, and that Spring, when initializing your service, find a constructor that requires an IConfig object to be injected. And therefore, it blows my mind: kotlin context receivers might integrate very well with spring ecosystem, without any evolution required Spring side. – amanin Jun 30 '23 at 12:05
  • @amanin . ya , There may be multiple context receivers. It's an interesting feature. – smallufo Jun 30 '23 at 14:32
  • I am testing spring bean injection through kotlin context receiver in [a small demo project](https://github.com/alexismanin/spring-kt-ctx-receiver-demo). It looks like it works well for `@Bean` annotated methods, but not so well for constructor injection. Well, in fact, it works with constructor injection only if the project does not use kotlin spring plugin and kotlin reflect lib (because in that case, it rely on plain "java" constructor binding, instead of trying to make clever guesses based on additional Kotlin metadata. – amanin Jun 30 '23 at 14:45

0 Answers0