Last active
April 1, 2021 12:31
-
-
Save derkork/95c4476bc780e6260672 to your computer and use it in GitHub Desktop.
Spring constructor dependency injection: Java vs. Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With Java, it's a lot of boilerplate code if you want to do it right and have your dependencies | |
// injected via the constructor instead of annotating private variables. | |
// see also: http://olivergierke.de/2013/11/why-field-injection-is-evil/ | |
@Component | |
public class Sample { | |
private SomeDependency someDependency; | |
@Autowired | |
public Sample(SomeDependency someDependency) { | |
Assert.notNull(someDependency, "someDependency must not be null"); | |
this.someDependency = someDependency; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With Kotlin, you can have it with no boilerplate at all. | |
@Component | |
open class Sample @Autowired (val someDependency:SomeDependency) { | |
} |
As mentioned here, both @Autowired and constructor can be dropped with the use @component and thus making the code even better and neat :
@component
open class Sample (val someDependency:SomeDependency) {
}
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or:
@component
open class Sample @Autowired constructor(val someDependency:SomeDependency) {
}