JP
08/04/2020, 1:35 PM@Autowired
with Kotlin,
I’m confused whether this
@Autowired
private lateinit var userService: UserService
is a field injection or a setter injection.
In the documentation, the Kotlin equivalent of both field and setter injection of Java were all in this fashion.
I read that field injection should be avoided, and I’ll try to stick with constructor injection if possible, but I’m just trying them out to learn.
If there is actually like a more stricter equivalents, I’d like to know how to write them in Kotlin.
Can anyone shed some light on this to me?thanksforallthefish
08/04/2020, 1:39 PMvar
in kotlin generates setter and getter and since your user service is not part of the constructor setter injection will be usedthanksforallthefish
08/04/2020, 1:41 PM@Component
class MyBean(private val userService: UserService)
will use constructor injection (and a final user service). in modern spring, when using constructor injection and there is only one constructor, you don’t even have to use @Autowired
, that just to show how much constructor injection is preferredJP
08/04/2020, 1:43 PM@Autowired
for newer Spring versions, it was more of a theoretical question.JP
08/04/2020, 1:44 PMthanksforallthefish
08/04/2020, 1:46 PM@field:Autowired
would bypass the setterthanksforallthefish
08/04/2020, 1:48 PMval
or var
. when you do val
you need to initialize at construction time, so with spring it will always be construction injection. when you do var
a setter is always (and here is where I am not sure) is always created for you and you can use lateinit
thus enabling setter injectionJP
08/04/2020, 1:49 PMYou can also apply theannotation to traditional setter methods, as the following example shows:@Autowired
class SimpleMovieLister {
@Autowired
lateinit var movieFinder: MovieFinder
// ...
}
You can applyto fields as well and even mix it with constructors, as the following example shows:@Autowired
class MovieRecommender @Autowired constructor(
private val customerPreferenceDao: CustomerPreferenceDao) {
@Autowired
private lateinit var movieCatalog: MovieCatalog
// ...
}
Ed M
08/06/2020, 2:23 PMthanksforallthefish
08/07/2020, 6:31 AMprivate
. eh eh, sometimes eyes can gloss over words in a pretty significant way. I am anyway cross posting this to the #spring channel, they are mixing public and private fields without a note highlighting the difference and even though in hindsight it is obvious I think one extra line might prevent such confusion in the futurethanksforallthefish
08/07/2020, 6:31 AM