Kotlin Spring 5: Dependency Injection Part 4 (@Profile)
Kotlin Spring 5: Dependency Injection Part 3 (@Primary)
Technologies used: Kotlin 1.2.10 | Spring 5 | Maven 3.3.9 | Spring-boot 2.0.0.M7
In this fourth post, we will look into the @Profile annotation for Spring Dependency Injection
In Spring framework, the @Profile
annotation is used to give higher preference to a bean, when there are multiple beans of same type but with different languages.
The @Profile
annotation may be used on any class directly or indirectly annotated with @Component
or on methods annotated with @Bean
.
The following examples demonstrate the use of the @Profile
annotation.
With a GreetingService interface
package vn.finixasia.didemo.services interface GreetingService { fun sayGreeting(): String }
Two Service Implementations EnglishGreetingService and ItalianGreetingService
package vn.finixasia.didemo.services
import org.springframework.stereotype.Service
@Service
@Profile("en")
class EnglishGreetingService : GreetingService {
private val HELLO_GURUS = "Hello from English !!!"
override fun sayGreeting(): String {
return HELLO_GURUS
}
}
And
package vn.finixasia.didemo.services
import org.springframework.stereotype.Service
@Service
@Profile("it")
class ItalianGreetingService : GreetingService {
private val HELLO_GURUS = "Ciao dall'inglese !!!"
override fun sayGreeting(): String {
return HELLO_GURUS
}
}
With my Controller MyController
package vn.finixasia.didemo.controllers
import org.springframework.stereotype.Controller
import vn.finixasia.didemo.services.GreetingService
@Controller
class MyController constructor(var greetingService: GreetingService) {
fun hello(): String {
return greetingService.sayGreeting()
}
}
We run with our Main App
package vn.finixasia.didemo
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import vn.finixasia.didemo.controllers.MyController
@SpringBootApplication
class DiDemoApplication
fun main(args: Array) {
var ctx = SpringApplication.run(DiDemoApplication::class.java, *args)
var controller = ctx.getBean("myController") as MyController
controller.hello()
ctx.close()
}
We get an error as Spring doesn’t found any GreetingService implementation, we need to add on our application.properties file
spring.profiles.active=it
If we run again, we get the output
Ciao dall'inglese !!!!
If we didn’t have any active profile, then we would get again the same error. The solution is to set a default bean as follow
@Profile("en", "default")
Now if we launch it work