I'm currently trying to figure out how to use the setter injection of Spring with Kotlin. I cannot use constructor injection for this because the Bean might be null and I don't want to use field injection because it's the worst. The obvious way to write
var x : Any? = null
@Autowired
set(value) {
x = value
}
cannot work because this will result in a cyclic call. So how can I autowire a member using setter injection?
The solution for this is a bit hard to find simply because I never wrote a setter for Kotlin so far. The problem is that one easily confuses the property with the backing field which is also generated by the compiler.
Thus the correct code is
var x : Any? = null
@Autowired(required = false)
set(value) {
field = value
}
The required = false
is necessary to make the injection optional, by the way.