Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin : Optional Dependency Injection Using Spring

What is the kotlin alternative for

@Autowired(required=false)
private DependencyC dependencyC;

and

private Optional<HelloService> optionalHelloService;
public HelloController(Optional<HelloService> helloService) {
    this.optionalHelloService = helloService;
}
like image 425
Abbin Varghese Avatar asked Oct 21 '25 15:10

Abbin Varghese


1 Answers

The accepted answer is outdated. Spring uses the type information to infer whether a bean is optional. See https://docs.spring.io/spring/docs/current/spring-framework-reference/languages.html#kotlin-annotations, specifically

In a similar fashion, Spring bean injection with @Autowired, @Bean, or @Inject uses this information to determine if a bean is required or not.

Because @Autowired is optional for constructor parameters, the shortest Kotlin alternative is

class HelloController(private val optionalHelloService: HelloService?)
like image 178
r33tnup Avatar answered Oct 23 '25 07:10

r33tnup