Reputation: 2678
I have a Spring Boot 2 + Kotlin application opened with IntelliJ 2019.1.
In this application I annotate some Kotlin objects with @Component
. Example:
@Component
object MyObject: MyInterface {
// code
}
I have many different implementation of MyInterface
(all with Kotlin objects) and I want to inject all of them in a list in another bean. Example:
@Component
class MyComponent @Autowired constructor(private val objects: List<MyInterface>) {
// code
}
The code runs correctly (the beans are inject in the list objects
) but IntelliJ shows an error saying:
Could not autowire. No beans of '? extends MyInterface' or 'List<? extends MyInterface>' types found.
If I change 'object' to 'class' at 'MyObject', the error disappears.
My questions are:
@Component
?Upvotes: 2
Views: 4083
Reputation: 3453
I would recommend not to use kotlin objects with @Component
or any other bean annotation.
There are two aspects and heaving a mix of them leads to lots of problems:
ApplicationContext
instances in your application.ClassLoader
Upvotes: 2
Reputation: 2678
For information, as a possible workaround while the ticket created by Николай in this answer is not treated, I'm ignoring the error/warning only where I need with @Suppress("SpringJavaInjectionPointsAutowiringInspection")
. Example:
@Suppress("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private lateinit var kotlinObjectBeans: List<MyInterface>
I hope it can help others that don't want to disable this check elsewhere.
Upvotes: 2
Reputation: 917
It is a little bit strange to use Kotlin objects as @Component
-s, because if your class knows that it will be used inside Spring-container you'll get more flexibility if you delegate to Spring the decision should this class be a singleton or not and all the other lifecycle management.
But practically I don't see any reason why it could be "not recommended" if you know what you are doing, and aware of probably bugs if your object
become stateful.
So I think IDEA should support your case, and I've filled up a ticket IDEA-211826
Upvotes: 1