Kotlin:使用 Spring 的可选依赖注入

Abb*_*ese 4 spring dependency-injection kotlin

kotlin 的替代品是什么

@Autowired(required=false)
private DependencyC dependencyC;
Run Code Online (Sandbox Code Playgroud)

private Optional<HelloService> optionalHelloService;
public HelloController(Optional<HelloService> helloService) {
    this.optionalHelloService = helloService;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

接受的答案已过时。Spring 使用类型信息来推断 bean 是否是可选的。具体请参见 https://docs.spring.io/spring/docs/current/spring-framework-reference/languages.html#kotlin-annotations

以类似的方式,使用 @Autowired、@Bean 或 @Inject 的 Spring bean 注入使用此信息来确定是否需要 bean。

因为@Autowired构造函数参数是可选的,所以最短的 Kotlin 替代方案是

class HelloController(private val optionalHelloService: HelloService?)
Run Code Online (Sandbox Code Playgroud)