Europe: +41 78 715 83 09 - Asia: +84 ‎975 112 112


31 Dec 2017

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


interface GreetingService {

    fun sayGreeting(): String

Two Service Implementations  EnglishGreetingService and ItalianGreetingService


import org.springframework.stereotype.Service

class EnglishGreetingService : GreetingService {
    private val HELLO_GURUS = "Hello from English !!!"

    override fun sayGreeting(): String {
        return HELLO_GURUS



import org.springframework.stereotype.Service

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

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

class DiDemoApplication

fun main(args: Array) {
    var ctx =, *args)
    var controller = ctx.getBean("myController") as MyController

We get an error as Spring doesn’t found any GreetingService implementation, we need to add on our file

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

Leave a Reply

Translate »