I'm trying to create an extension function whose implementation uses a Spring bean. It didn't seem possible to do this by defining the extension function at the top level of a package. I tried this:
@Component
class Converter {
companion object {
@Autowired
lateinit var transformer: Transformer
fun Class1.convert(): Class2 {
return Class2 (this, transformer.transform(someStringProperty))
}
}
}
where transform
is a function that transforms some string to another string, and Class1
is some class that has a someStringProperty
property. My hope was that other classes could import pkg.Converter.Companion.convert
and then be able to use x.convert()
where x
is an object of type Class1
.
The syntax works, and using x.convert()
in other classes compiles fine. But it results in an exception at run time: kotlin.UninitializedPropertyAccessException: lateinit property transformer has not been initialized
It looks like Spring isn't autowiring the variable because it's in a companion object and not an actual component object.
Annotating the companion object with @Component
didn't work.
I don't think moving Class1.convert
directly inside Converter
would work, because then using x.convert()
would need an instance of the Converter
object, and I don't see how to do this with the extension function syntax.
Is there any way to accomplish this, or do I have to give up on the extension function syntax?