When changing the Controller of Spring Web MVC to kotlin, @Autowired The specified component is not injected and becomes null.

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.

Postscript

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

When changing the Controller of Spring Web MVC to kotlin, @Autowired The specified component is not injected and becomes null.
The official name of Spring MVC is Spring Web MVC
About the solution to the problem that the log of logback is not output when the web application is stopped
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
Library not loaded when trying to upgrade the version of ruby and rails s
When the hover of Eclipse is hard to see
I tried to summarize the basics of kotlin and java
The idea of cutting off when the error is not resolved
[Rails] When the layout change of devise is not reflected
Throw an exception and catch when there is no handler corresponding to the path in spring