Kotlin Spring: Unresolved reference method - spring

I have the following class in file A:
#Service
class MyService(
private val myLoader: Loader
) {
fun load(myKey: SomeKey) =
myLoader.loadStuff(myKey)
}
I want to call that function in another file B like so:
MyService.load(myKey)
However, the load() method is marked red in IntelliJ. The error says "Unresolved reference: load" and I can't figure out why. When I type MyService. IntelliJ even suggests the load method.
How can I resolve this issue?

Since you are using Spring, the other component that should call MyService must also be a Spring-managed Bean so that it can get a hold of the MyService bean. Your component in the file B should look as follows:
#Service
class MyServiceB (
private val myService: MyService
) {
fun test(myKey: SomeKey) = myService.load(myKey)
}
Mind the #Service annotation that makes it a Spring-managed Bean and also the fact that MyService is an argument of MyServiceB constructor, telling Spring that a Bean of type MyService must be injected.
Given that you have an object instead of a class, you will have to do something like the following:
object MyServiceB (
lateinit var myService: MyService
) {
fun test(myKey: SomeKey) = myService.load(myKey)
}
#Configuration
class MyServiceBConfiguration(private val myService: MyService) {
#Bean
fun myServiceB(): MyServiceB {
return MyServiceB.also {
it.myService = myService
}
}
}
This should work but I definitely do not recommend it. This is a hack and definitely not a clean solution. Consider my initial suggestion.

Related

Is there a way to overide automatically injected beans in Spring boot when writing tests?

I have a class annotated with a spring bean #Repository("clientDatasource") called ClientServiceDatasource which implements an interface called Datasource. I also have a mock implementation of this interface also annotated with a spring bean #Repository("mockDatasource") called MockClientServiceDatasource. I also have a class annotated with the spring bean #Service called ClientService and in in its constructor, I pass in a datasource. I do it like so:
#Service
class ClientService (#Qualifier("clientDatasource") private val dataSource: Datasource){}
As you can see that the service will default to the clientDatasource, because of the #Qualifier when the application is running.
However when I run my tests I annotate my test class with #SpringTest . In my understanding this means that it boots up the entire application as if it were normal. So I want to somehow overide that #Qualifier bean thats being used in the client service in my test so that the Client Service would then use the mockedDatasource class.
I'm fairly new to kotlin and spring. So I looked around and found ways to write a testConfig class to configure beans like so :
#TestConfiguration
class TestConfig {
#Bean
#Qualifier("clientDatasource")
fun mockDatasource(): Datasource {
return MockClientServiceDatasource()
}
}
and then using it in the test like so:
#SpringTest
#Import(TestConfig::class)
class ClientServiceTest {
...
}
I also asked chatGPT and it gave me this:
#SpringBootTest
class ClientServiceTest {
#Autowired
lateinit var context: ApplicationContext
#Test
fun testWithMockedDatasource() {
// Override the clientDatasource bean definition with the mockDatasource bean
val mockDatasource = context.getBean("mockDatasource", Datasource::class.java)
val mockClientDatasourceDefinition = BeanDefinitionBuilder.genericBeanDefinition(MockClientServiceDatasource::class.java)
.addConstructorArgValue(mockDatasource)
.beanDefinition
context.registerBeanDefinition("clientDatasource", mockClientDatasourceDefinition)
// Now the ClientService should use the mockDatasource when it's constructed
val clientService = context.getBean(ClientService::class.java)
// ... do assertions and other test logic here ...
}
}
But some of the methods don't work, I guess chatGPT knowledge is outdated.
I also looked through spring docs, but couldn't find anything useful.
Okay, So I took a look at the code previously with the TestConfig class. And I realised by adding the:
#Primary
annotation to the method inside my TestConfig class, it basically forces that to be the primary repository bean. Like so:
#TestConfiguration
class TestConfiguration {
#Bean
#Primary
#Qualifier("clientDatasource")
fun mockDatasource(): Datasource {
return MockClientDataSource()
}
}
and in the test I only imported the test and it just worked. I didn't have to autowire anything
This is my test class:
#SpringBootTest
#AutoConfigureMockMvc
#Import(TestConfiguration::class)
internal class ServiceControllerTest{
#Suppress("SpringJavaInjectionPointsAutowiringInspection")
#Autowired
lateinit var mockMvc: MockMvc
#Test
fun `should return all clients` () {
// when/then
mockMvc.get("/clients")
.andDo { print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$[0].first_name") {value("John")}
}
}
}

Hilt - Inject a list of Interface implementations

Let me show what I mean by code.
Interface:
interface MyInterface {
}
I have 2 implementation classes:
#Singleton
class Implementation1 #Inject constructor(
private val gson: Gson,
) : MyInterface {
}
#Singleton
class Implementation2 #Inject constructor(
#ApplicationContext private val context: Context,
) : MyInterface {
}
I need a repository class with list of implementations of MyInterface:
#Singleton
class MyRepository #Inject constructor(
private val implementations: List<MyInterface>,
) {
}
Problem part: I am trying to inject as below:
#InstallIn(SingletonComponent::class)
#Module
object MyDiModule {
#Provides
fun providesImplementations(
imp1: Implementation1,
imp2: Implementation2,
): List<MyInterface> {
return listOf(imp1, imp2)
}
}
But I get compilation error:
/home/sayantan/AndroidStudioProjects/example/app/build/generated/hilt/component_sources/debug/com/example/ExampleApplication_HiltComponents.java:188: error: [Dagger/MissingBinding] java.util.List<? extends com.example.MyInterface> cannot be provided without an #Provides-annotated method.
public abstract static class SingletonC implements FragmentGetContextFix.FragmentGetContextFixEntryPoint,
^
Any way to achieve this?
This might be late but would like to drop my thoughts.
Firstly, you need to annotate your #Provides methods in the module class because dagger would certainly throw an error of multiple bindings of MyInterface.
For example:
enum class ImplType {
Impl1, Impl2
}
#Qualifier
#Retention(AnnotationRetention.RUNTIME)
annotation class ImplTypeAnnotation(val type: ImplType)
#Singleton
#Provides
#ImplTypeAnnotation(ImplType.Impl1)
fun provideImplementation1(impl1: Implementation1): MyInterface
// Do the same for Implementation2
Secondly, once these are done, you need to individually inject them into the Repository class. e.g.
class MyRepository #Inject constructor(
#ImplTypeAnnotation(ImplType.Impl1) private val implementation1: MyInterface,
#ImplTypeAnnotation(ImplType.Impl2) private val implementation2: MyInterface
) {
// get the implementations as list here using Kotlin listOf()
}
NB: I'm not sure if providing List<MyInterface> would work.
Hope this helps!
I do not know how correct this answer is, but it works for me, so posting as answer.
This can be done using the annotation #JvmSuppressWildcards.
In the above example, everything is fine, I just need to add this annotation to the class where the dependencies are being injected, i.e. the MyRepository class.
#JvmSuppressWildcards
#Singleton
class MyRepository #Inject constructor(
private val implementations: List<MyInterface>,
) {
}
I was seeing the same problem in the project I've been working on, but moving from List<> to Array<> seemed to fix it for me.
So in your case the hilt injection would look like:
#Provides
fun providesImplementations(
imp1: Implementation1,
imp2: Implementation2,
): Array<MyInterface> {
return arrayOf(imp1, imp2)
}
Then used with:
#Singleton
class MyRepository #Inject constructor(
private val implementations: Array<MyInterface>,
) {
}

how to approach Spring boot constructor based dependency injection confusion/frustration when unit testing a component class with several dependencies

I am trying to write unit tests for a Spring boot service using JUnit 4 and Mockito.
I used constructor based dependency injection for my service, The Signature is:
class VbServiceImp(val jdbcTemplate: NamedParameterJdbcTemplate,
val nuanceService: NuanceService,
val conf: AppConfigProps,
val eventService: EventServiceImp,
val audioTrimService: AudioTrimServiceIF,
val vbNuanceStagingDeletionsService: VbNuanceStagingDeletionsService) : VbService {...}
in another part of the application This service gets injected into a controller and somehow spring just magically knows what to inject without me specifying this (Any idea how this works/explanation would be appreciated, guess it's based on component scan?)
example:
class VbController(val vbService: VbService) {...}
Now in my VBServiceImpl Unit test class I try to mock all the above dependencies before declaring vBService in order to manually inject all dependencies into VBService during declaration.
the relevant part of my test class looks like this:
#RunWith(SpringRunner::class)
#ContextConfiguration()
class VBServiceTests {
#MockBean
val jdbcTemplate: NamedParameterJdbcTemplate = mock()
#MockBean
val nuanceService: NuanceService = mock()
#MockBean
val appconfigProps: AppConfigProps = AppConfigProps()
#MockBean
val eventService: EventServiceImp = mock()
#MockBean
val audioTrimService: AudioTrimService = mock()
#MockBean
val vbNuanceStagingDeletionsService: VbNuanceStagingDeletionsService = mock()
val vbService: VbServiceImp = VbServiceImp(jdbcTemplate, nuanceService, appconfigProps, eventService, audioTrimService, vbNuanceStagingDeletionsService)
#SpyBean
val vbServiceSpy: VbServiceImp = Mockito.spy(vbService)
#Before
fun setup() {
initMocks(this)
}
When I run a test I get the exception below. If I understand this correctly there is already a bean of type jdbcTemplate in the application context and therefore I can't define the #Mockbean jdbcTemplate above?
exception:
private final org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate com.cc.ff.vb.service.VBServiceTests.jdbcTemplate cannot have an existing value
So now the issue is: If I removed the #MockBean jdbcTemplate variable then I can't inject jdbcTemplate when I declare vbService in my test class. So how could I get around this/make this work?
Just to check I removed the jdbcTemplate parameter from the vbService class constructor and changed it to a #Autowired field injected class variable and provided the mock class using #TestConfig. This worked however then the exception popped up on the next constructor parameter (NuanceService)
i'm out of ideas and google hasn't returned anything of value. Do I remove all constructor injected dependencies and then make them field injected using #Autowired and then provide the beans in the nested #TestConfig annotated class or is there a better/cleaner way? AFAIK field based injection is supposed to be bad practice?
example of providing correct bean for testing #Autowired field injected jdbcTemplate variable:
#TestConfiguration
class testConfig {
#Bean
fun jdbcTemplate(): NamedParameterJdbcTemplate {
return mock<NamedParameterJdbcTemplate>()
}
}
This is how I ended up making it work:
#TestConfiguration
class testConfig {
#Bean
fun jdbcTemplate(): NamedParameterJdbcTemplate {
return mock<NamedParameterJdbcTemplate>()
}
#Bean
fun nuanceService(): NuanceService {
return mock<NuanceService>()
}
#Bean
fun appConfigProps(): AppConfigProps {
return mock<AppConfigProps>()
}
#Bean
fun eventService(): EventServiceImp {
return mock<EventServiceImp>()
}
#Bean
fun audioTrimService(): AudioTrimService {
return mock<AudioTrimService>()
}
#Bean
fun vbNuanceStagingDeletionService(): VbNuanceStagingDeletionsService {
return mock<VbNuanceStagingDeletionsService>()
}
}
#MockBean
lateinit var nuanceService: NuanceService
#SpyBean
lateinit var vbServiceSpy: VbServiceImp
I'm still not sure if this is the best/optimal way of going about this so would appreciate some more details...

Kotlin with Spring DI: lateinit property has not been initialized

I don't get Spring-based setter dependency injection in Kotlin to work as it always terminates with the error message "lateinit property api has not been initialized". I could reduce the problem to the following scenario: There is an interface
interface IApi {
fun retrieveContent(): String
}
which is implemented by
class Api : IApi {
override fun retrieveContent() = "Some Content"
}
I want to use the implementation in another class where the dependency injection is supposed to take place:
#Component
class SomeController {
#Autowired lateinit var api: IApi
fun printReceivedContent() {
print(api.retrieveContent())
}
}
However, the application terminates with the above-mentioned error message. My Spring config looks as follows:
#Configuration
open class DIConfig {
#Bean
open fun getApiInstance(): IApi = Api()
}
In the main function I load the application context and call the method:
fun main(args: Array<String>) {
val context = AnnotationConfigApplicationContext()
context.register(DIConfig::class.java)
context.refresh()
val controller = SomeController()
controller.printReceivedContent()
}
What is the problem here?
Spring isn't involved if you just call the constructor yourself like that. Same as in Java,
val controller = context.getBean(SomeController::class.java)
Spring Framework 5.0 adds Kotlin extensions, so you could also write either one of
val controller = context.getBean<SomeController>()
val controller: SomeController = context.getBean()
your api is currently no a bean managed by spring, try annotating it with #Service or #Component
The #Autowired is usually added to the setter of a property. So instead of using it for the property, you should explicitly annotate the setter:
#set:Autowired lateinit var api: IApi

How to use spring annotations like #Autowired in kotlin?

Is it possible to do something like following in Kotlin?
#Autowired
internal var mongoTemplate: MongoTemplate
#Autowired
internal var solrClient: SolrClient
Recommended approach to do Dependency Injection in Spring is constructor injection:
#Component
class YourBean(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
) {
// code
}
Prior to Spring 4.3 constructor should be explicitly annotated with Autowired:
#Component
class YourBean #Autowired constructor(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
) {
// code
}
In rare cases, you might like to use field injection, and you can do it with the help of lateinit:
#Component
class YourBean {
#Autowired
private lateinit var mongoTemplate: MongoTemplate
#Autowired
private lateinit var solrClient: SolrClient
}
Constructor injection checks all dependencies at bean creation time and all injected fields is val, at other hand lateinit injected fields can be only var, and have little runtime overhead. And to test class with constructor, you don't need reflection.
Links:
Documentation on lateinit
Documentation on constructors
Developing Spring Boot applications with Kotlin
Yes, java annotations are supported in Kotlin mostly as in Java.
One gotcha is annotations on the primary constructor requires the explicit 'constructor' keyword:
From https://kotlinlang.org/docs/reference/annotations.html
If you need to annotate the primary constructor of a class, you need to add the constructor keyword to the constructor declaration, and add the annotations before it:
class Foo #Inject constructor(dependency: MyDependency) {
// ...
}
You can also autowire dependencies through the constructor. Remember to annotate your dependencies with #Configuration, #Component, #Service etc
import org.springframework.stereotype.Component
#Component
class Foo (private val dependency: MyDependency) {
//...
}
like that
#Component class Girl( #Autowired var outfit: Outfit)
If you want property injection but don't like lateinit var, here is my solution using property delegate:
private lateinit var ctx: ApplicationContext
#Component
private class CtxVarConfigurer : ApplicationContextAware {
override fun setApplicationContext(context: ApplicationContext) {
ctx = context
}
}
inline fun <reified T : Any> autowired(name: String? = null) = Autowired(T::class.java, name)
class Autowired<T : Any>(private val javaType: Class<T>, private val name: String?) {
private val value by lazy {
if (name == null) {
ctx.getBean(javaType)
} else {
ctx.getBean(name, javaType)
}
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value
}
Then you can use the much better by delegate syntax:
#Service
class MyService {
private val serviceToBeInjected: ServiceA by autowired()
private val ambiguousBean: AmbiguousService by autowired("qualifier")
}

Resources