hichem rtibi
hichem rtibi

Reputation: 3

How to use profile in Spring-boot application?

I want to use profile in Spring-boot application. I don't know how to do it.

How to modify the following code ?

package com.example.demo;
import org.springframework.stereotype.Component;

@Component
public class EnglishGreeting implements HelloWorldService {

    @Override
    public String greeting() {
        // TODO Auto-generated method stub
        return "hello world";
    }

}

package com.example.demo;

import org.springframework.stereotype.Component;

@Component
public class SpanichGreeting implements HelloWorldService {

    @Override
    public String greeting() {
        // TODO Auto-generated method stub
        return "hola monda";
    }

}

Any suggestion ?

Upvotes: 0

Views: 82

Answers (2)

Steven Diamante
Steven Diamante

Reputation: 217

In addition to adding @Profile("en") and @Profile("es") you must create property files called application-en.properties and application-es.properties.

You can create a property in each file for example:

application-en.properties

greeting.text=hello world

application-es.properties

greeting.text=hola monda

And in your service add a variable that takes that value in.

Like this:

@Component
public class SpanishGreeting implements HelloWorldService {

@Value("${greeting.text})"
String greeting

      @Override
      public String greeting() {
          // TODO Auto-generated method stub
          return this.greeting;
      }
}

More info about @Value here: https://www.baeldung.com/spring-value-annotation

Upvotes: 0

Kayaman
Kayaman

Reputation: 73568

If your intention is to select either one implementation depending on the profile, you need to add the annotations.

@Component
@Profile("en")
public class EnglishGreeting implements HelloWorldService

@Component
@Profile("es")
public class SpanichGreeting implements HelloWorldService {

Running the program with -Pes would enable the es profile, and it would use the spanish implementation when autowiring.

Upvotes: 1

Related Questions