Skip to content

Instantly share code, notes, and snippets.

@derkork
Last active April 1, 2021 12:31
Show Gist options
  • Save derkork/95c4476bc780e6260672 to your computer and use it in GitHub Desktop.
Save derkork/95c4476bc780e6260672 to your computer and use it in GitHub Desktop.
Spring constructor dependency injection: Java vs. Kotlin
// 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;
}
}
// With Kotlin, you can have it with no boilerplate at all.
@Component
open class Sample @Autowired (val someDependency:SomeDependency) {
}
@fhchina
Copy link

fhchina commented Apr 14, 2019

or:
@component
open class Sample @Autowired constructor(val someDependency:SomeDependency) {
}

@neo182
Copy link

neo182 commented Jun 20, 2019

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) {
}

@mazend
Copy link

mazend commented Apr 1, 2021

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment