Pedro Henrique
Pedro Henrique

Reputation: 191

Dynamically inject class in spring

I want to inject a class dynamically based on the argument of my method call

I`ve try use AspectJ and different annotations of Spring

I need a solution like that:

@Component
class MyUseCase(private val spi: MySpiPort) {

    fun myAction() {
        spi.doSomething("myId")
    }
}

interface Injectable

interface MySpiPort : Injectable {
    fun doSomething(id: String)
}


class MyProxyClass {

    //will intercept all Injectable
    fun resolver(id: String): MySpiPort {
        if(id == "myId"){
            //inject MyFirstImpl
        }else{
            //inject MySecondImpl
        }
        TODO("not implemented")
    }

}

@Component
class MyFirstImpl : MySpiPort {
    override fun doSomething(id: String) {
        TODO("not implemented") 
    }
}

@Component
class MySecondImpl : MySpiPort {
    override fun doSomething(id: String) {
        TODO("not implemented")
    }
}

I expect inject just a common interface of the implementations, I don't want inject in MyUseCase Class a FactoryBean Class or something like that.

Upvotes: 1

Views: 410

Answers (1)

Elisha Ebenezer
Elisha Ebenezer

Reputation: 57

You can leverage Spring's Conditional injection. Please refer https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-java-conditional

Upvotes: 2

Related Questions