The original article is here.
Suppose you have a Java class like the one below.
@Controller
@Scope("request")
@RequestMapping("/foo/bar")
public class FooBarController: Foo() {
    @Autowired
    FooBarService fooBarService;
    @RequestMapping(method = RequestMethod.GET)
    public String foo() {
        return fooBarService.doSomething();
    }
}
If you automatically convert this to koilin, it will look like this.
@Controller
@Scope("request")
@RequestMapping("/foo/bar")
class FooBarController {
    @Autowired
    internal var fooBarService: FooBarService? = null
    @RequestMapping(method = arrayOf(RequestMethod.GET))
    fun foo(): String {
        return fooBarService!!.doSomething()
    }
}
If this is left as it is, Autowired of fooBarService will not work and it will remain null.
So, as answered in here ,
@Controller
@Scope("request")
@RequestMapping("/foo/bar")
open class FooBarController(val fooBarService: FooBarService) {
    @RequestMapping(method = [RequestMethod.GET])
    open fun foo(): String {
        return fooBarService.doSomething()
    }
}
Autowired will work by adding open to class and fun. I also removed @Autowired, moved it to the constructor, and made the method arrays a bracket. It's more beautiful.
If you use kotlin-spring as described in here, it will be automatically added to the class with @Component inheritance annotation. It seems that it gives open to the target.
buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
    }
}
apply plugin: "kotlin-spring" // instead of "kotlin-allopen"
Recommended Posts